I am just starting out with Unity. I have created 4 gameObjects, each has a single sprite attached to it. One of the gameObjects is my player and has its own class, the other 3 are instances of a different class. The player object moves with your finger, using Input.GetTouch. I want the 3 non-player sprites to move away from my player. In theory, this shouldn’t be hard. I’m writing in 2D, so if the x position of the non-player is less than the player’s x position, it should decrease, else it should increase. Same with the y position. But I have been trying to get this to work for 3 days with no luck. The player object moves correctly, if far too fast. But the non-player objects seem to move randomly if at all. Sometimes, only one moves. Here are my classes. Can anyone see what is wrong with my logic?
Player class:
public Vector2 current;
public Vector2 previous;
// Start is called before the first frame update
void Start()
{
current = transform.position;
}
// Update is called once per frame
void Update()
{
previous = current;
if (Input.touchCount > 0)
{
Touch playerTouch = Input.GetTouch(0);
if (playerTouch.phase == TouchPhase.Moved)
{
current = playerTouch.position;
current = (Camera.main.ScreenToWorldPoint(current));
this.transform.position = current * Time.deltaTime;
}
}
}
Non-player class:
public Vector2 obj_position;
private Vector2 previous;
public PlayerBehaviourScript player;
// Start is called before the first frame update
void Start()
{
obj_position = transform.position;
}
// Update is called once per frame
void Update()
{
previous = obj_position;
if(player != null && player.current != player.previous)
{
if (player.current.x < obj_position.x)
{
obj_position.x = (obj_position.x + (player.current.x));
}
if(player.current.x > obj_position.x)
{
obj_position.x = (obj_position.x - (player.current.x));
}
if (player.current.y < obj_position.y)
{
obj_position.y = (obj_position.y + (player.current.y));
}
if (player.current.y > obj_position.y)
{
obj_position.y = (obj_position.y - (player.current.y));
}
transform.position = obj_position * Time.deltaTime;
}
}