- Home /
Keep a min distance away from object while moving towards it
I have game where a player moves in spaces kinda like a chess board. And every time the player moves two objects also move following him. How I did this is I have him move with the press of an arrow key and then I put a script on the other objects that say when an arrow key is pressed move towards the object and it works great. But I need to keep them from getting to close to him and this is where im having trouble. I tried to do a set up like this:
if(transform.position.x >= 0)
{
if(Mathf.Abs(currCam.transform.position.x) - Mathf.Abs(transform.position.x) < minDistance)
{
float setFromCamX = (Mathf.Abs(currCam.transform.position.x) - Mathf.Abs(transform.position.x) - minDistance) * 1;
transform.position = new Vector3(transform.position.x + setFromCamX, transform.position.y, transform.position.z);
}
}
else
{
if(Mathf.Abs(currCam.transform.position.x) - Mathf.Abs(transform.position.x) < minDistance)
{
float setFromCamX = (Mathf.Abs(currCam.transform.position.x) - Mathf.Abs(transform.position.x) - minDistance) * -1;
transform.position = new Vector3(transform.position.x + setFromCamX, transform.position.y, transform.position.z);
}
}
What that does is it checks where both objects are at, then it will subtract or add distance to set them a mid distance away from him and keep the object on the correct side. But my objects always end up as a diagonal away from him. So what is a better way to approach this problem?
Your question is about 'flocking'. I've not needed to use it myself, but hopefully this will help you:
http://forum.unity3d.com/threads/maintain-$$anonymous$$imum-distance-from-others.49604/
may i ask you how did you maintain the movement of your player ? actually using the same method to move all objects and using same speed variables should end up with linear and no distance reducing movement.
Player movement is based on already set coordinates in the game. Object movements are done through Vector3.$$anonymous$$oveTowards
And that link was close but not quite what i need. The problem is the enemys bunch up on the player
This should help.....I THIN$$anonymous$$ https://www.assetstore.unity3d.com/en/#!/content/21626 https://www.assetstore.unity3d.com/en/#!/content/14437