- Home /
How to move sprites in the opposite direction to player.
I have a sprite on the screen, that is static in its position and when I use the keys/controller it rotates in the direction it is supposed to go in. For testing purposes I have another sprite that is moving in the x direction with the following code.
protected virtual void Step()
{
Vector3 direction = new Vector2(Mathf.Sin(Mathf.Deg2Rad * 90), Mathf.Cos(Mathf.Deg2Rad * 90));
Vector3 position = transform.position;
position.x += direction.x * 2 * Time.deltaTime;
position.y += direction.y * 2 * Time.deltaTime;
transform.position = position;
}
This is an abstract class that can be inherited by other objects, to provide different speeds. So the sprite on the screen then has this in the code.
private void Update()
{
Step();
}
protected override void Step()
{
base.Step();
Vector3 direction = new Vector2(Mathf.Sin(Mathf.Deg2Rad * playerScript.oppositeDirection()), Mathf.Cos(Mathf.Deg2Rad * playerScript.oppositeDirection()));
position = transform.position;
position.x += direction.x * 4 * Time.deltaTime;
position.y += direction.y * 4 * Time.deltaTime;
if (position.x > 16)
{
position.x = -16;
}
transform.position = position;
}
For testing purposes I have it wrapping back to the left of screen once it goes of the screen on the right.
Now the player script, has a public field that is supposed to get the opposite direction the player is going in and provide the second sprite a different movement. To explain this, think of the player sprite moving towards the sprite then the sprite would appear to arrive at the player quicker. If the player is going away from the other sprite, then it is supposed to gradually move away from the other sprite.
The code on the player script, is as follows.
private void FixedUpdate()
{
if (yRot != 0 || xRot != 0)
{
angle = Mathf.Atan2(yRot, xRot) * Mathf.Rad2Deg;
quat = Quaternion.Euler(0f, 0f, -angle);
transform.rotation = Quaternion.LerpUnclamped(transform.rotation, quat, rotationSpeed * Time.deltaTime);
}
}
public float oppositeDirection()
{
Vector3 direction = transform.rotation.eulerAngles;
return (direction.z + 180) % 360;
}
And of course the same should be true if the player is moving up or down the screen, the parent class should keep the player moving across the screen and if they player moves up towards the other sprite, then it moves towards that sprite, if I am moving down the screen the the player is supposed to move away from the other sprite.
I am not getting this to work the way I am hoping it too. Anyone have any idea?
A simple context would be to get the vector between the player (transform) and the sprite (transform) and invert the normalize vector of that vector ?
Vector3 vec = player.transform.position - other.transform.position;
vec = vec.normalize;
other.tranform.Translate(-vec * speed);