- Home /
Making a pong-like game, and want the ball to reflect according to where on the paddle it hits
(Pretty new to programming) I have made my ball so that it bounces off of the players, and the walls. But Instead of having the angle which it bounces off of the player to be equal to the approach-angle, i want the ball to reflect off of the player according to where on the player it hits. Have looked at other questions like this, but haven't come across one that could help me.
Here's what i got so far:
private void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.tag == "Player")
{
if (speed < 50)
speed+=0.5f;
Debug.Log ("AUCH!");
}
// Normal
Vector3 N = col.contacts[0].normal;
//Direction
Vector3 V = velocity.normalized;
// Reflection
Vector3 R = Vector3.Reflect(V, N).normalized;
// Assign normalized reflection with the constant speed
rigidbody2D.velocity = new Vector2(R.x, R.y) * speed;
}
You don't define how the hit position varies the reflection, so it is hard for anyone to give you an accurate answer. The easiest solution would be to define some sort of function that varies the normal of the surface based on position, and then to use that varied normal in your Vector3.Reflect().
Can i use Vector3 when everything else is Vector2 and it's made with unity's 2D...stuff?
Answer by BrandonD · Apr 21, 2014 at 09:16 PM
I recently made a pong game that does just this, here's the code I used:
function OnCollisionEnter(coll:Collision){
var contact=coll.contacts[0];
var contactHeight:float=Mathf.Round((coll.transform.position.y-transform.position.y)*100);// Negative values mean on top
if(coll.transform.tag=="Player"){
if(goingLeft){
goingLeft=false;
}
else{
goingLeft=true;
}
speed+=Mathf.Abs(contactHeight/80);
vertSpeed+=(contactHeight/-20);
}
if(coll.transform.tag=="Wall"){
vertSpeed=-vertSpeed;
}
if(Mathf.Abs(vertSpeed)>speed*maxVertSpeedFactor){
vertSpeed=Mathf.Clamp(vertSpeed,-speed*maxVertSpeedFactor,speed*maxVertSpeedFactor);
}
}