Bouncing off Walls in C#

Hey everybody. I’m stumped on a physics related question. I created a player controller and couldn’t get the feel I needed out of Unity’s built-in physics, so I coded my own movement, but that also leaves me without some of the benefits of the built-in physics.

The problem I have is that I want this controller to bounce off walls following simple, standard angle of incidence. Because I’m directly translating the vehicle, physics materials and bounce are not helpful. I’m pretty sure Vector3.Reflect can help, but I’m not sure how to employ it.

My Player Controller script (a tank-style vehicle with forward movement and rotation) does the following for movement:

void Movement()
{	
	float moveForward = spd * Time.smoothDeltaTime * mov;
	transform.Translate(Vector3.forward * moveForward);
}

And this for rotation:

void Rotation()
{
	float rotate = rot * Time.smoothDeltaTime * Input.GetAxis("Horizontal");
	transform.Rotate(Vector3.up * rotate);
}

What I need is for it to hit a wall at any angle and be pushed away at the reflection of that angle and equal velocity. Because I’m not using any sort of physics force (except for jumping), the vehicle will hit a wall and just keep trying to press through it.

But how do I get the angle and velocity at which I make the impact in 3D space using my hand-coded movement?

Note: I am using gravity for a jump function, which means OnCollisionEnter becomes problematic. Basically, I’m controlling my vehicle horizontally with direct translation and, and its vertical movement (jumping) with a basic rigidbody force and physics

You can keep track of your velocity pretty easily:

Vector3 myLastPosition;

void Update() {
  // movement goes here
  myLastPosition = transform.position;
}

public Vector3 Velocity {
  get {
    return (transform.position-myLastPosition)/Time.deltaTime;
  }
}

A perfect bounce is super easy:

newVelocity = Vector3.Reflect(oldVelocity, impactNormal);