- Home /
Pong Game: Vector (0,y) question
Hey guys! I'm a newb attempting to build a Pong game using this tutorial.
However, I'm encountering a problem where my Vector2 will sometimes directly return a (0,y) in it's x, resulting in the ball just bouncing back and forth in a straight line. I also encounter this when it hits at an obtuse angle against my topWall and bottomWall collision objects. Do you guys have any suggestions/psuedocode that could prevent this? I'm at a loss.
For reference:
My hitFactor function: (takes relative position of ball -> player and defines a new vector in my Collision2D function)
float hitFactor (Vector2 ballPos, Vector2 racketPos, float racketHeight) {
return (ballPos.y - racketPos.y) / racketHeight;
}
And my Collision2D function:
void OnCollisionEnter2D (Collision2D coll) {
//Collision of Ball v. Paddle
if (coll.gameObject.name == "Player1") {
float y = hitFactor(transform.position, coll.transform.position, coll.collider.bounds.size.y);
//new Vector2 with length=1 and calculate new velocity
Vector2 dir = new Vector2(1,y).normalized;
rigidbody2D.velocity = dir * speed;
}
if (coll.gameObject.name == "Player2") {
float y = hitFactor(transform.position, coll.transform.position, coll.collider.bounds.size.y);
//new Vector2 with length=1 and calculate new velocity
Vector2 dir = new Vector2(-1,y).normalized;
rigidbody2D.velocity = dir * speed;
}
}
That last bit on the "Float y" line is "coll.collider.bounds.size.y". It's formatting it out for some reason.
Thanks for any help you can give!
Your answer
Follow this Question
Related Questions
Problems with Initial Velocity 0 Answers
Internal collisions 1 Answer
Detect Object At on Vector2 1 Answer
Non - Physics collision System 0 Answers
Random.Range issue 1 Answer