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. Dismiss Notice

Increasing speed variable with Rigidbody2d

Discussion in '2D' started by OPuniverse, Jan 15, 2015.

  1. OPuniverse

    OPuniverse

    Joined:
    Oct 25, 2014
    Posts:
    3
    Hi all,

    I'm a newcomer to game development and programming. I'm having trouble trying to increase the speed of a ball using rigidbody2D. I saw the speed variable increases in the inspector-view but in game-view the speed stays the same. Please see my code below. Could you tell me what's wrong? Thanks in advance :)
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class BallControl : MonoBehaviour
    5. {
    6.  
    7.      public float speed = 2.0f;
    8.      Vector2 v2;
    9.  
    10.      void Start ()
    11.      {
    12.           //random direction at the start
    13.           float x = Random.Range(-10.0f,10.0f);
    14.           float y = Random.Range(-10.0f,10.0f);
    15.           v2 = new Vector2 (x, y);
    16.           rigidbody2D.velocity = v2.normalized * speed;
    17.      }
    18.  
    19.      void FixedUpdate()
    20.      {
    21.           //increment the speed
    22.           speed++;
    23.      }
    24. }
    25.  
     
  2. vakabaka

    vakabaka

    Joined:
    Jul 21, 2014
    Posts:
    1,153
  3. Elmdran

    Elmdran

    Joined:
    Oct 28, 2014
    Posts:
    34
    Like vakabaka said, your speed is only set once inside the Start function, which is only called once. Your variable increases each update with FixedUpdate but you're not increasing the rigidbodys velocity after the start function.

    So move line 16 into your fixedupdate and it will work ;)
     
  4. OPuniverse

    OPuniverse

    Joined:
    Oct 25, 2014
    Posts:
    3
    Hey,

    Thanks for the replies. I've added in the new line in the script but the ball is acting weird now. The ball object has a physical material with bounciness of 1. Before the changes, the ball bounces off the collision wall. After adding in "rigidbody2D.velocity = v2.normalized * speed;" under "speed++", the ball just stuck to the wall. Here's a picture.
     

    Attached Files:

  5. Elmdran

    Elmdran

    Joined:
    Oct 28, 2014
    Posts:
    34
    Well now you're constantly adding force to the ball, so looking at the code the ball should fly around like crazy. What is it you want to happen?
     
  6. OPuniverse

    OPuniverse

    Joined:
    Oct 25, 2014
    Posts:
    3
    Hi,

    What I want to do is increasing the ball speed over time and make the ball bounce around the wall that has been set up.