Sign up ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I am trying to make an AI that tries to move towards the player but I don't know how. I tried using Vector2.MoveTowards() but it just mimics my movements instead of moving towards the player. I tried everything i could think of (which was not a lot :D) but i couldn't make it move towards and touch the player! Help please :D.

Also my original code:

#pragma strict
var speed : float = 100;
var targetX : Transform;
var targetY : Transform;
var mex : Transform;
var meY : Transdorm;
function Update ()
{
var targetX = transform.position.x;
var targetY = transform.position.y;
var meX = transform.position.x;
var meY = transform.position.y;
Vector2.MoveTowards(Vector2(meX, meY), Vector2(targetX, targetY), speed);
}
share|improve this question

2 Answers 2

up vote 1 down vote accepted

Hey there are couple of things which you are missing out.

1) Even thought the motion is in 2d plane but the gameobject dimension is 3D, so use Vector3 instead of Vector2

2) When you calculate Vector3 Movetowards it returns a value which is calculated upon current position , target position and speed.

This needs to be assigned to the transform of the AI. Link:- http://docs.unity3d.com/ScriptReference/Vector3.MoveTowards.html

Here is the code: This script needs to be put on AI object , and assign the player variable through inspector.

 var player : GameObject;
 var speed : float;

function Start () 
{
    speed = 10;
}

function Update () 
{
    gameObject.transform.position = Vector3.MoveTowards(gameObject.transform.position, player.transform.position  , Time.deltaTime*speed);
}
share|improve this answer

Your targetX and targetY are being set as your current script's transform.position, rather than your target's position.

Also, targetX and targetY are Transforms, when really it sounds like they should be floats, or perhaps even just simplified as a single var target : Transform;. You could also just have var me : Transform; as well.

Your MoveTowards should also multiply speed by Time.deltaTime to make the movement be framerate-independent.

#pragma strict
var speed : float = 100;
var target : Transform;
var me : Transform;

function Update ()
{
    Vector2.MoveTowards(me.position, target.position, speed * Time.deltaTime);
}

Note that you will need to define both target and me either in the Inspector or within a script.

share|improve this answer
    
Nope.. it didn't solve it... It basically did the same thing. Is there a better way to make something try to touch you? Becouse I tried everything with this function and nothing worked. – ElPolloLoco999 Aug 20 at 16:47

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.