Maintain constant altitude (make object follow ground)

Hey guys!

I have a game in which tanks can shoot bullets at other tanks. The levels will include ramps for these tanks to drive on to platforms and what not.

I have been trying to create a script, that would enable the bullets to follow the ground, so that you would be able to shoot your opponent even if he is on higher grounds, but only if you shoot up a ramp.

My code at the moment looks something like this. It checks for collision with ground and objects below and tries to alter the velocity:

if(Physics.Raycast(transform.position, Vector3.down, out hit, raycastDistance, layer)){
  if(hit.distance < altitudeToMaintain){
    rigidbody.AddForce(Vector3.up * (altitudeToMaintain-hit.distance), ForceMode.VelocityChange);
  }else{
    rigidbody.AddForce(Vector3.down * (hit.distance-altitudeToMaintain), ForceMode.VelocityChange);
  }
}

I think I need to consider the velocity as well, as it spins out of control when the velocity.y != 0.

Is there anyone out there, who could help me with calculating the right forces to add?

There’s a script attached to this thread that shows how to float an object a fixed distance above the ground. It is actually controlling a camera in this case, but the approach is more or less the same.

1 Like

Thank you very much! I will try to give your script a spin.

Am I correct when assuming, that I will only need to apply the hoverSpring to my object?

It works! It took a little tweaking of the spring-properties to get it right.

This is the code I’m using:

RaycastHit hit;

//Hovering.		
Vector3 hoverForce = Vector3.zero;

if (Physics.Raycast(transform.position, Vector3.down, out hit, raycastDistance, layer)) {
  hoverForce = hoverSpring.Reaction(transform.position, hit.point, rigidbody.velocity);
}

rigidbody.AddForce(hoverForce, ForceMode.VelocityChange);

Once again thank you! :slight_smile: