I have an object that moves based on AddRelativeForce in a given direction. The object changes direction slightly and the force is added via FixedUpdate(). Now, I want to make this object change direction when it hits a wall. Put shortly, I want the object to change direction in a way that perfectly mirrors the direction of the collision, like this.
The FixedUpdate() function would take care of moving the object in this new direction.
So far, I have this code:
private int count;
public int moveSpeed = 500;
public float maxVelocity = 10.0f;
private float lookSpeed = 15.0f;
// rotation variables
private float rotationX = 0.0f;
private float rotationY = 0.0f;
void Start ()
{
count = 0;
}
void FixedUpdate ()
{
//alter direction slightly every 5 counts
if (count == 5)
{
rotationX += Random.Range (-0.2f, 0.2f) * lookSpeed;
rotationY += Random.Range (-0.2f, 0.2f) * lookSpeed;
rotationY = Mathf.Clamp (rotationY, -90, 90);
transform.localRotation = Quaternion.AngleAxis (rotationX, Vector3.up);
transform.localRotation *= Quaternion.AngleAxis (rotationY, Vector3.left);
count = 0;
}
count++;
//apply force in given direction, with limit
if (rigidbody.velocity.magnitude > maxVelocity)
{
rigidbody.velocity = rigidbody.velocity.normalized * maxVelocity;
}
rigidbody.AddRelativeForce(moveSpeed * Vector3.forward);
}
//reflect off wall
void OnCollisionEnter(Collision collision)
{
if (collision.collider.tag == "wall") {
ContactPoint hit = collision.contacts[0];
Vector3 reflection = Vector3.Reflect (rigidbody.velocity, hit.normal);
rotationX = reflection.x;
rotationY = reflection.y;
}
}
As it stands, however, the object tends to turn in the direction of the object it is colliding with. i.e.: it’s running right into it.
Is there something wrong with my code?
Thanks in advance!