- Home /
Trying to make object bounce off walls - gets stuck!
I'm trying to make the object controlled by the player (a rocket) bounce off walls when it strikes them. For that, my code is this:
void OnCollisionEnter(Collision collision)
{
foreach(ContactPoint contact in collision.contacts)
{
velocityfix = Quaternion.AngleAxis(180, contact.normal) * velocityprefix * -1;
velocityfix.y = 0;
}
Debug.Log(collision.collider.name);
}
void OnCollisionStay(Collision collision)
{
foreach (ContactPoint contact in collision.contacts)
{
velocityfix = Quaternion.AngleAxis(180, contact.normal) * velocityprefix;
velocityfix.y = 0;
}
}
In update:
if (velocityfix != new Vector3(0, 0, 0))
{
transform.Translate(velocityfix);
velocityfixx = velocityfix;
velocity = velocityfix;
velocityfix = new Vector3(0, 0, 0);
}
else
{
transform.Translate(velocity);
velocityprefix = velocity;
velocity.y = 0;
}
This should cause the object to bounce off the wall, as the collider is at the front of the object. Instead, what happens is that the object hits the plane, and starts jittering. Sometimes it gets stuck in the plane, and then when it gets free, it starts moving off-axis. I've basically hard-coded it to move in the direction it's pointing (velocityfix is only used on collision; velocity.x and velocity.y are set to solid values elsewhere). What's going on here? Is there a better way of dealing with changes in angle and velocity on collision?
Answer by $$anonymous$$ · May 12, 2014 at 03:24 PM
You cant use transform.Translate().
Attach rigidbody to your gameObject
Call rigidbody.AddForce();
I'm not sure how I would use that in this case. I'm trying to keep a constant forward speed; all I really need is to turn when I hit the wall...