- Home /
Move object along waypoints, but affected by gravity
Hello,
I am trying to move an object along a series of waypoints, in a line. The typical solution is this:
function Update() {
transform.LookAt(targetGO.transform);
var distance : float = speed * Time.deltaTime;
var source : Vector3 = transform.position;
var target : Vector3 = targetGO.transform.position;
transform.position = Vector3.MoveTowards(source, target, distance);
if(Vector3.Distance(source, target) < ARRIVE_DISTANCE)
targetGO = pathManager.NextWaypoint(targetGO);
}
This works great for moving from one waypoint to the next, however, it does not take into account gravity. For my scene, I am dynamically created waypoints along a path on the terrain. I would rather the character controller move towards each waypoint, but stay affixed to the ground (unless he's jumping). So the basic algorithm I'm thinking would be:
-get next waypoint
-if there is horizontal input, calculate movement towards next waypoint
-after calculation, add gravity factor
-move towards that target, and rotate towards it
What is the most effective solution to do this? Should I not be using MoveTowards, but instead do something like this:
//somehow change moveDirection to take into account gravity?
Vector3 moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, 0);
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
//apply gravity
moveDirection.y -= gravity * Time.deltaTime;
Vector3 move = moveDirection * Time.deltaTime;
controller.Move(move);
Any help is appreciated! Thanks, Ryan
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220613104751im_/https://answers.unity.com/themes/thub/images/avi.jpg)