Question by
Spellking · Feb 23, 2021 at 09:31 AM ·
2d gamelookrotation
how to make 2d sprite flip vertically while looking at the mouse
I've got a 2d player sprite for a top-down shooter game that is supposed to flip vertically to face the mouse, and he is supposed to "hold" a gun sprite that is supposed to constantly point directly at the mouse. However, they both don't work properly at some angles and I can't figure out why. This is the code for the player:
void Start() { localScale = transform.localScale; }
void Update()
{
pMovement.x = Input.GetAxisRaw("Horizontal");
pMovement.y = Input.GetAxisRaw("Vertical");
animator.SetFloat("Horizontal", pMovement.x);
animator.SetFloat("Vertical", pMovement.y);
animator.SetFloat("Speed", pMovement.sqrMagnitude);
mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
}
void FixedUpdate()
{
playerRB.MovePosition(playerRB.position + pMovement * moveSpeed * Time.fixedDeltaTime);
Vector2 lookDir = mousePos - playerRB.position;
float angle = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg - 90f;
if (angle > 0)
{
transform.localScale = new Vector3(localScale.x, localScale.y, localScale.z);
}
else if (angle < 0)
{
transform.localScale = new Vector3(-localScale.x, localScale.y, localScale.z);
}
}
and this is the code so far for the gun:
void FixedUpdate() { rb.MovePosition(rb.position + movement moveSpeed Time.fixedDeltaTime);
Vector2 lookDir = mousePos - rb.position;
float angle = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg;
if (transform.position.x <= 0)
{
rb.rotation = angle;
}
else if (transform.position.x > 0)
{
rb.rotation = angle;
}
}
void Update()
{
movement.x = Input.GetAxisRaw("Horizontal");
movement.y = Input.GetAxisRaw("Vertical");
mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
}
}
Any help would be greatly appreciated! I am kind of a noob and learned C# for this project, so it's still all very new to me. Thanks for any help!
Comment
Your answer
