- Home /
Make an object move towards a Player
I have been trying to make an ai that goes to the player and attacks him, and I have looked up tutorials on how to do it but they all use a patrol system, which I don't want to use.heres what I have so far using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Deformed : MonoBehaviour {
Rigidbody2D rb2D;
Rigidbody2D playerRb2D;
Transform trans;
Transform playerTrans;
public float Distancebetween;
public GameObject player;
void Start () {
rb2D = gameObject.GetComponent<Rigidbody2D> ();
trans = gameObject.GetComponent<Transform> ();
playerTrans = player.GetComponent<Transform> ();
playerRb2D = player.GetComponent<Rigidbody2D> ();
}
// Update is called once per frame
void Update () {
Distancebetween = playerTrans.position.x - trans.position.x;
if (Distancebetween != 0){
rb2D.AddForce( Vector2.right * playerRb2D.velocity.x);
}
}
}
I am not sure what the question is.
The only issue I can see is the fact that you never use Distbetween, ins$$anonymous$$d you base the enemies force off the players velocity, which won't really get the enemy moving towards the player.
Perhaps something like this will work for you?
rb2D.AddForce( Vector2.right * $$anonymous$$athf.Sign(Distancebetween) * 100f);
You will have to tweak the force (100f) to get it right, if its not moving, try making this super high.
Also try changing Update to FixedUpdate, as the AddForce functions are really designed to be called from FixedUpdate().
Answer by ZeN12 · Jul 18, 2017 at 07:37 AM
public static int movespeed = 1; public Vector3 userDirection = Vector3.right; public Start() { } public void Update() { transform.Translate(userDirection * movespeed * Time.deltaTime); }
Need to detect userDirection before moving.
@ZeN12 all it does is move right
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Deformed : $$anonymous$$onoBehaviour {
public static int movespeed = 1;
public Vector3 userDirection = Vector3.right;
public void Start() {
}
public void Update() {
transform.Translate(userDirection * movespeed * Time.deltaTime);
}
}
Yes, now in updateLoop you need to detect where it should go. Update{ if (playerTrans.postion.x > transform.position.x){ userDirection = Vector3.right; }else{ userDirection = Vector3f.left; } transform.Translate(userDirection * speed * Time.deltaTime); }
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612130529im_/https://answers.unity.com/themes/thub/images/avi.jpg)