- Home /
GameObject1 move away when GameObject2 gets close
I currently have a script which (in 2D space) tells my enemy GameObject to chase after my target (the player). I want it so when the enemy gets too close or when the player moves towards it, it dodges out of the way.
In my code I effectively just said the opposite of the 'chase' code (so when it gets too close, move in the opposite direction of the players location).
When I test it, the enemies:
move towards the player normally (which is fine)
as soon as they hit minimum distance they immediately move back to their original location
if I DO manage to move my character on top of one it flickers constantly
Any ideas? Is there another function that will allow for just moving in a random direction AWAY from the target when I'm within a certain range?
Thanks guys!
using UnityEngine;
using System.Collections;
public class GuardianKnightMeleeController : MonoBehaviour
{
public Transform target;
public float speed = 5f;
private float minDistance = 3f;
private float range;
void Update()
{
range = Vector2.Distance(transform.position, target.position);
if (range > minDistance)
{
transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
}
if (range < minDistance)
{
transform.position = -Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
}
}
}
Answer by maccabbe · Feb 04, 2016 at 03:53 AM
-Vector2.MoveTowards does not define moving away but scaling the position by -1. Instead multiply the maxDistanceDelta by -1 as that will push the vector away from target, i.e.
transform.position = Vector2.MoveTowards(transform.position, target.position, -1 * speed * Time.deltaTime);
http://docs.unity3d.com/ScriptReference/Vector2.MoveTowards.html
Thank you friend! When I was doing it I'm like 'there is no way this would work' so your explanation makes sense!
Thanks so much! ^_^