- Home /
How do i make something reflect in 2D?
I can't make my ball in Pong bounce off of the player when they collide. I have a pretty decent idea of how to do it in 3D, and tried something similar, but it doesn't work. Right now the ball just bounces (almost) straight upwards, after colliding with the player, no matter where on the player it hits.
Here's what i got:
public class Ball : MonoBehaviour { private Vector2 moveDirection; public float MoveSpeed; // Adjusts direction ball flies after hitting paddle public float PadDirectionAdjust;
// Use this for initialization
void Start () {
moveDirection = Vector2.right;
}
// Update is called once per frame
void Update () {
transform.position = new Vector2(transform.position.x, transform.position.y);
// Translates the gameObject according to direction and move speed
transform.Translate(moveDirection * MoveSpeed * Time.deltaTime, Space.World);
// Destroys gameObject if it goes out of screen
if (transform.position.x >= 12)
{
Destroy(gameObject);
}
}
void OnCollisionEnter2D(Collision2D coll)
{
// If ball hits paddle
if (coll.gameObject.tag == "Player")
Debug.Log ("AUCH!");
{
if (MoveSpeed<40)
MoveSpeed++;
Vector2 hitpoint = coll.contacts[0].point;
BoxCollider2D padCollider = coll.collider as BoxCollider2D;
Vector2 padCenter = padCollider.transform.TransformPoint(padCollider.center);
padCenter.y -= PadDirectionAdjust;
Vector2 newDirection = hitpoint - padCenter;
moveDirection = newDirection.normalized;
return;
}
moveDirection = Vector3.Reflect(moveDirection.normalized, coll.contacts[0].normal).normalized;
moveDirection = new Vector2 (moveDirection.x, moveDirection.y);
Answer by Yorgi · Dec 13, 2016 at 10:59 PM
try this one
private Vector2 inDirection; private float speed = 1f;
public void Start()
{
inDirection = new Vector2(Random.Range(-1f, 1f), Random.Range(-1f, 1f));
}
public void FixedUpdate()
{
transform.Translate(inDirection * speed, Space.World);
}
public void OnCollisionEnter2D(Collision2D collision)
{
var contactPoint = collision.contacts[0].point;
Vector2 ballLocation = transform.position;
var inNormal = (ballLocation - contactPoint).normalized;
inDirection = Vector2.Reflect(inDirection, inNormal);
}
O$$anonymous$$G man i have been search for this code more than 3 days THAN$$anonymous$$ YOU!
Your answer
Follow this Question
Related Questions
Unity 2D-¿How do I make a bullet bounce off the wall? 4 Answers
Making a pong-like game, and want the ball to reflect according to where on the paddle it hits 1 Answer
Why does my reflect code not work? 1 Answer
pong question 2 Answers
Bounce value not change in script for 2D object in Unity4.3. 1 Answer