- Home /
How can I make a flying object follow ground player and stay airborne?
Basically I have a police helicopter that is airborne, and a player-controlled car on the ground. The helicopter would be supposed to follow the car but stay airborne, basically locking the Y axis. I don't care about collisions for this, so if Y axis is locked is fine by me, since i'd prefer to not give the helicopter collision. Below is the code. I'm aware that by using LookAt() and by adding forward it is going to move on all axis, so my question is how can I make it to move only on X and Z, with Y being locked in order to keep the helicopter airborne.
using UnityEngine; using System.Collections;
public class PoliceHelicopterController : MonoBehaviour {
public float MinDistance = 35;
public float MaxDistance = 10;
public float Speed = 7;
public Transform Player;
void Update () {
transform.LookAt(Player);
if (Vector3.Distance(transform.position, Player.position) >= MinDistance)
{
transform.position += transform.forward * Speed * Time.deltaTime;
}
}
}
Thanks.
Answer by qjoman · Oct 20, 2016 at 01:16 PM
Use [Vector3.MoveTowards]
. This will give you a position, moving from a given position (first parameter) to the given target (second parameter) using a step (third parameter).
I can't run the script right now, but I think it'll be something like this:
public class PoliceHelicopterController : MonoBehaviour {
public float MinDistance = 35;
public float MaxDistance = 10;
public float Speed = 7;
public Transform Player;
void Update () {
transform.LookAt(Player);
if (Vector3.Distance(transform.position, Player.position) >= MinDistance)
{
Vector3 follow = Player.position;
//setting always the same Y position
follow.y = this.transform.position.y;
// remenber to use the new 'follow' position, not the Player.transform.position or else it'll move directly to the player
this.transform.position = Vector3.MoveTowards(this.transform.position, follow, Speed * Time.deltaTime);
}
}
}
Just like 15 $$anonymous$$s ago I tried $$anonymous$$oveTowards and it worked! Thanks anyway, I'm sure your answer might help other people as well.
Answer by Dune2 · Oct 19, 2016 at 11:18 PM
Use only the X & Z axis of the player in your following object update.
IE, something like
var p = player.position;
p.y = follow.position.y; // So follow keeps its altitude
follow.position = p;
That works almost perfectly. The only issue is that the helicopter gets on top of the car instantly, since follow.position = p. What should I use to move to the player object based on the Speed property? So that it follows the player, based on X and Z, but does not instantly reach to it.
Your answer
Follow this Question
Related Questions
Rotating an object around Z axis using Lerp 2 Answers
Look At while locked in a position 1 Answer
Move player along mesh 0 Answers
Creating a multiple part turret what locks onto certain axis. 4 Answers
How to lock the y axis in camera script? 2 Answers