- Home /
Movement between waypoints?
So I'm moving a cube between waypoints, now my problem is that i only want it to align itself with the waypoints along the xaxis, i don't want it to float through the air to reach them and I want gravity to remain active whilst it moves between them.
Heres my code so far:
var waypoint: Transform[]; var speed : float = 20; private var currentWaypoint:int;
var loop : boolean = true;
function Awake(){ waypoint[0] = transform ; } function Update () { if(currentWaypoint < waypoint.length){ var target : Vector3 = waypoint[currentWaypoint].position; var moveDirection : Vector3 = target - transform.position;
var velocity = rigidbody.velocity;
if(moveDirection.magnitude < 1){
currentWaypoint++;
}
else{
velocity = moveDirection.normalized * speed;
}
}
else{
if(loop){
currentWaypoint = 0;
}
else{
velocity = Vector3.zero;
}
}
rigidbody.velocity = velocity;
}
How would I go about doing this?
Answer by Tetrad · Jun 19, 2010 at 05:17 PM
It sounds like you want to have your object moving along the ground (is the ground flat?) and just moving to where the waypoint would be projected onto the ground (use Physics.Raycast
to determine where that is by raycasting up or down).
A simple thing to do that might work is to change your rigidbody math to instead use AddForce
instead of using .velocity directly. (This is to let gravity and collision stuff do its trick.) Maybe make your vertical component of the vector you calculated to go to the next waypoint zero so it doesn't apply force upwards. Maybe change the physics properties of your collider so it slides across the ground easier. There are lots of little things you can play around with if you have a small set of requirements.
(Also, rigidbody updates should go in FixedUpdate
, not Update
.)
These suggestions are pretty naive, honestly, and you really should look into more advanced pathfinding solutions: http://answers.unity3d.com/questions/tagged/pathfinding
The aligning to the x axis is easy, just do transform.rotation = Quaternion.Euler( target.transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, transform.rotation.eulerAngle.z );
(Although you'll probably want to use some kind of lerping from the Quaternion class to make the rotation smooth.)
Why not transform.rotation = target.transform.rotation ?
@Herman, since if you do that you won't guarantee that you're facing up.
@Tetrad Oh, now I see (skim$$anonymous$$g over the line, I thought all the angles were on the target)
can object be made to move between two waypoints in air so that object seems to fly while moving from one waypoint to other ?
Your answer
![](https://koobas.hobune.stream/wayback/20220613062504im_/https://answers.unity.com/themes/thub/images/avi.jpg)