- Home /
Lock Homing Missile to Plane (2D)
I am trying to make a missile that follows the player, one that rotates towards the direction of the player and generally acts as a homing missile does. The homing code works fine. However, it's a 2D game and I find my missile doing loop-de-loops onto the Z-axis when trying to find my player even though I want the missile to be bound to the X-Y plane.
Here is the code i'm using for the homing enemy (javascript)
var target : Transform;
var moveSpeed = 4;
var rotationSpeed = 1;
var life = 0;
function Awake()
{
}
function Start()
{
target = GameObject.FindWithTag("Player").transform;
transform.rotation = Quaternion.LookRotation(target.position - transform.position);
}
function FixedUpdate()
{
var lookDir = target.position - transform.position;
//lookDir.z = 0;
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(lookDir), rotationSpeed*Time.deltaTime);
transform.position += transform.forward * moveSpeed * Time.deltaTime;
}
function Update()
{
life = life + 1;
if (life > 300)
{
Destroy(gameObject);
}
}
you'll notice the lookDir.z = 0 code commented out. This was my attempt at fixing it, however the code caused odd things to occur.
Again, homing itself works fine, but how do I lock the missile to the x-y plane, preventing them from moving in the z-direction at all?
You need to explain how the missile was a constructed. In particular, you need to explain what side of the missile is considered forward.
The Forward side is always rotating or trying to rotate to face the player.
Have you ever found a solution to this? I'm having the same problem, having a hard time solving it.
Yes. Your missile should have a rigidbody2D
public GameObject player; //your missile's target
public float speed = 1;
private Vector2 dist = new Vector2();
void Update () {
dist = player.transform.position - transform.position; //difference in space between target and player
dist = dist.normalized; //makes sure it's based on direction. Without it, the missile slows down the closer the missile is to target.
rigidbody2D.AddForce (dist * speed);
}
Play with rigidbody2D settings like mass, drag, and angular drag to get the effect you want.
Answer by hav_ngs_ru · Dec 22, 2014 at 02:55 PM
I guess, the Missile and Player z-coords are not exactly the same. In this case missile should twitch of cause.
Try to set transform.positino.z = target.transform.position.z in Start (before calculate rotation). And in FixedUpdate too (to avoid changing of z because of float round operations).