Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

.AddForce() won't launch ball?

Discussion in 'Scripting' started by g_mister, May 11, 2015.

  1. g_mister

    g_mister

    Joined:
    Dec 5, 2012
    Posts:
    12
    I watched the following tutorial and decided to put together a Brick Breaker type game myself but 2D. I have the paddle working but I can't get the ball to launch.

    Here is my code:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Ball : MonoBehaviour {
    5.  
    6.      public float ballInitialVelocity = 1f;
    7.      private Rigidbody2D rb;
    8.      private bool ballInPlay;
    9.    
    10.      void Awake () {
    11.        
    12.          rb = GetComponent<Rigidbody2D>();
    13.        
    14.      }
    15.    
    16.      void Update ()
    17.      {
    18.          if (Input.GetButtonDown("Fire1") && ballInPlay == false)
    19.          {
    20.              transform.parent = null;
    21.              ballInPlay = true;
    22.              rb.isKinematic = false;
    23.              rb.AddForce(new Vector2(ballInitialVelocity, ballInitialVelocity), ForceMode2D.Force);
    24.          }
    25.      }
    26. }
    Not sure what I'm missing here, any help is appreciated.

    Thank you for your time!
     
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    Increase the velocity.

    --Eric
     
    g_mister likes this.
  3. g_mister

    g_mister

    Joined:
    Dec 5, 2012
    Posts:
    12
    Thanks!

    Two things:

    1. I increased the velocity to 600f and it flew off the screen

    2. AFTER actually adding the script to the ball itself...

    yeah -__-

    Thanks again!
     
  4. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    Step 2 is a killer. Although I've never ever done that myself. Nope nope nope. Not ever. ;)

    --Eric