I've got a ball object and I want to be able to manipulate the ball's speed (both speed up and slow down) based on different pickups dropped in the game. I'm not sure how best to do this. Here is my code for the Ball class:
public class Ball : MonoBehaviour
{
private Paddle paddle;
private bool hasStarted = false;
private Vector3 paddleToBallVector;
// Use this for initialization
void Start ()
{
paddle = GameObject.FindObjectOfType<Paddle>();
paddleToBallVector = this.transform.position - paddle.transform.position;
}
// Update is called once per frame
void Update ()
{
if (!hasStarted)
{
//Lock the ball relative to the paddle.
this.transform.position = paddle.transform.position + paddleToBallVector;
//Wait for a mouse press to launch.
if (Input.GetMouseButtonDown (0))
{
hasStarted = true;
this.GetComponent<Rigidbody2D> ().velocity = new Vector2 (2f, 10f);
}
}
}
void OnCollisionEnter2D (Collision2D collider)
{
//use this vector2 to adjust the velocity so the ball does not get stuck in a vertical bouncing loop
Vector2 tweak = new Vector2 (Random.Range(0f, 0.2f),Random.Range(0f, 0.2f));
if (hasStarted)
{
AudioSource audio = this.gameObject.GetComponent<AudioSource>();
audio.Play();
this.gameObject.GetComponent<Rigidbody2D>().velocity += tweak;
}
}
}
I just need to know how to manipulate the speed for this class. I'm not sure if how I have it set up now is the best way to manage movement of the ball object or if I should modify it to accommodate for speed manipulation.