Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Simple 2D Homing Missile Help C# (no rigidbody)

Discussion in '2D' started by Tiatang, Sep 18, 2014.

  1. Tiatang

    Tiatang

    Joined:
    Jun 1, 2014
    Posts:
    31
    Hey, all i just want to create some simple homing missiles, so far i have rotation working nicely but i haven't managed proper movement :(
    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class AIFollow : MonoBehaviour {
    6.  
    7.    private GameObject Player;
    8.    public float Lag;
    9.    public float Speed;
    10.    public float Sensitivity;
    11.  
    12.    void Start () {
    13.      Player = GameObject.Find("SHip2"); // yes, the h is in caps
    14.    }
    15.  
    16.    void Update () {
    17.      StartCoroutine(RotateObj(transform,Player.transform.position));
    18.    }
    19.  
    20.    IEnumerator RotateObj(Transform obj, Vector3 playerpos) {
    21.      yield return new WaitForSeconds(Lag);
    22.      float orotation = Mathf.Rad2Deg * Mathf.Atan2(obj.position.y - playerpos.y ,transform.position.x - playerpos.x);
    23.      transform.rotation = Quaternion.Euler(0,0,orotation+90);
    24.    }
    25. }
    26.  
     
  2. Pyrian

    Pyrian

    Joined:
    Mar 27, 2014
    Posts:
    301
    Rotation is hands-down harder than movement, so congratulations on that. All you're doing is moving forwards, although in 2D "forwards" is not necessarily defined (it's based on the Sprite), so you might have to experiment a little if I didn't get this quite right:

    In Update:
    transform.position = transform.up * Time.deltaTime * Speed;

    If "up" wasn't right, try "right", or the negation of either. (Pretty sure "forward" just sends you haring off in the unused Z-axis.)
     
  3. imaginaryhuman

    imaginaryhuman

    Joined:
    Mar 21, 2010
    Posts:
    5,834
    For movement what I'd do is a) subtract the destination coordinate from the current coordinate to get a difference, b) convert that to an angle and distance, c) change the distance to a given movement speed * the delta timing adjustment, d) recalculate a new location using cos/sin and move the object there. There's probably better ways to do it I guess.
     
  4. Tiatang

    Tiatang

    Joined:
    Jun 1, 2014
    Posts:
    31
    Thanks for the help all managed to get it working but i had to remove the coroutine