Question by
IshanCK · Nov 21, 2017 at 11:41 PM ·
unity 52d gameerror build
My enemy is going the wrong way
My enemy is going the OPPISITE way of the character or just going southeast.
public float speed = 5f;
public Transform target;
public float rotateSpeed = 200f;
private Rigidbody2D rb;
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody2D> ();
}
// Update is called once per frame
void FixedUpdate () {
Vector2 direction = (Vector2)target.position - rb.position;
direction.Normalize ();
float rotateAmt = Vector3.Cross (direction, transform.up).z;
rb.angularVelocity = rotateAmt * rotateSpeed;
rb.velocity = transform.down * speed;
}
} `
Comment
Best Answer
Answer by NinjaISV · Nov 22, 2017 at 12:49 AM
The main problem here is that you are using transform.down
(which does not exist as far as I know) You need to use -transform.up
I've re-coded your script to work perfectly and show an example of how it works.
(New Script)
using UnityEngine;
public class FollowTarget : MonoBehaviour {
public Transform target;
[Space(6)]
public float speed = 2f;
public float rotateSpeed = 500f;
private new Rigidbody2D rigidbody;
// Use this for initialization
private void Start () {
rigidbody = GetComponent<Rigidbody2D> ();
}
// Update is called once per frame
private void FixedUpdate () {
Vector2 direction = ((Vector2) target.position - rigidbody.position).normalized;
float rotateAmt = Vector3.Cross (direction, transform.up).z;
rigidbody.angularVelocity = rotateAmt * rotateSpeed;
rigidbody.velocity = -transform.up * speed;
}
}
NOTE: You must ensure that gravity scale is set to 0 on the rigidbody:
Hope this helps you! Thanks!
unity-forums-follow-target-2d-example.gif
(409.0 kB)