- Home /
Ball doesn't increase speed. C#
I am creating a pong game just to test out Unity3D. So, every time the ball hits a racket, it's supposed to increase the speed. But when I do that the ball hits the racket several times, then it starts flying everywhere..
Can anyone help?
Here is the code:
using UnityEngine;
using System.Collections;
public class BallBehaviour : MonoBehaviour {
public float speed = 30f;
bool reset = false;
void Start(){
GetComponent<Rigidbody2D> ().velocity = Vector2.right * speed;
}
void Update(){
if (reset && Input.GetKeyUp (KeyCode.Space)) {
GetComponent<Rigidbody2D> ().velocity = Vector2.right * speed;
reset = false;
} else {
GetComponent<Rigidbody2D> ().velocity = Vector2.right * speed;
}
}
void OnCollisionEnter2D (Collision2D col){
if (col.gameObject.name == "Player 1" || col.gameObject.name == "Player 2") {
speed += 5f;
} else if (col.gameObject.name == "WallLeft") {
Reset();
} else if (col.gameObject.name == "WallRight") {
Reset();
}
}
void Reset () {
reset = true;
gameObject.transform.position = new Vector2 (0, 0);
GetComponent<Rigidbody2D> ().velocity = Vector2.zero;
}
}
$$anonymous$$aybe you can solve this by creating a variable that remembers what player the ball last collided with, so that the ball doesn't increase speed if it collides with the same player twice in a row.
Answer by zeppike · May 03, 2015 at 08:27 AM
For me the problem seems to be, that you always trying to set the velocity to the right. So after collision the standard physics system bounces back the ball, but you set the velocity to the right again in Update(). To achieve the desired effect in OnCollisionEnter2D() I would store the velocity in a temporary variable, modify the x value and write it back. Than eliminate the else closure from Update. Something like this:
void OnCollisionEnter2D (Collision2D col){
if (col.gameObject.name == "Player 1" || col.gameObject.name == "Player 2") {
speed += 5f;
Vector2 tmp = GetComponent<Rigidbody2D> ().velocity;
tmp.x += speed;
GetComponent<Rigidbody2D> ().velocity = tmp;
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613194515im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How to increase and decrease the animation speed? 1 Answer
Bullet not moving from script 3 Answers