- Home /
Ball wont go faster
Hello unity newbie here. I have a problem with one of my scripts. I´m trying to make a simple pong game where the ball will go faster everytime it hits one of the players. But the ball only goes slower! Here is my script:
using UnityEngine;
using System.Collections;
public class Ball : MonoBehaviour {
public int ballSpeed;
void Start () {
rigidbody.AddForce(new Vector3(Random.Range(-100.0F, 100.0F), 0, 0) * ballSpeed * Time.deltaTime);
}
void OnCollisionEnter (Collision col)
{
if(col.gameObject.name == "Player01")
{
float X = Random.Range(-5.0F, -15.0F);
float Y = Random.Range(6.0F, -6.0F);
ballSpeed += 100;
rigidbody.AddForce(new Vector3(X, Y, 0) * ballSpeed * Time.deltaTime);
}
else if(col.gameObject.name == "Player02")
{
float X = Random.Range(5.0F, 15.0F);
float Y = Random.Range(6.0F, -6.0F);
ballSpeed += 100;
rigidbody.AddForce(new Vector3(X, Y, 0) * ballSpeed * Time.deltaTime);
}
}
}
First thing I notice is that you aren't using the 2D physics components. Are your GameObjects in your scene setup with 2D colliders?
Answer by tanoshimi · Jun 10, 2014 at 06:25 PM
Two comments:
Firstly, I'd make ballSpeed a float. (i.e.
public float ballSpeed;
andballSpeed += 100f;
)I don't know why you're multiplying the force by Time.deltaTime, but I'd be almost certain that you don't want to, so try removing that from the force assignment. Time.deltaTime is generally used for changing values in a frame-independent manner, but it's not applicable here since AddForce is an instantaneous event. When you do remove this term, you'll probably need to adjust the scale of the other values, since you're currently multiplying the force by an arbitrary small number that's probably around 0.02.
Didnt work just started spas$$anonymous$$g out sometimes when colliding
What does "didn't work" mean? Didn't do anything? Gave an error message? Didn't speed up? You need to help us help you...
Answer by MissionCalice8 · Jun 10, 2014 at 06:55 PM
Do you know about colliders and triggers? Try putting a a collider on the paddles and the ball, then check "is trigger". I'm not sure if this will work. You'll have to add a tag to each of the paddles.
using UnityEngine; using System.Collections; public class Collider : MonoBehaviour { void OnTriggerEnter(Collider other) { if (other gameObject.tag == "Paddle") { rigidbody.AddForce(10, 10, 0); } } }
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Method keeps looping when using waitForSeconds 1 Answer
Need help with begginner script! 1 Answer
function Start () problem!! 3 Answers
I need help !!! -3 Answers