Question by
Shdow89 · Feb 24 at 10:53 PM ·
c#rigidbody2dmovement scriptdirection
2d Rigidbody how to check if Player is moving towards the mouse
Hey everyone,
Sorry if I'm asking a dumb question here, I'm making a top-down shooter in 2D, and I made a really messy code to control player movement. Now I ran into an issue that I'm trying to resolve and I would appreciate any help. What I need help with is to detect if the player is moving towards or opposite of the mouse direction. Since my script is always rotating the player towards the mouse position, I need something to help me figure out if the player is moving in the opposite direction that he is facing.
Any help would be greatly appreciated. Here's the messy code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[SerializeField] float moveSpeed = 15f;
[SerializeField] Camera cam;
private Rigidbody2D rb;
bool isRunning = false;
Animator anim;
Vector2 movement;
Vector2 mousePos;
Vector2 movePos;
void Awake() {
rb = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
}
void Update()
{
movement.x = Input.GetAxisRaw("Horizontal");
movement.y = Input.GetAxisRaw("Vertical");
mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
if (Input.GetKey(KeyCode.LeftShift))
{
isRunning = true;
} else
{
isRunning = false;
}
SetAnimationState();
handleRunningState();
}
void FixedUpdate() {
movePos = rb.position + movement.normalized * moveSpeed * Time.fixedDeltaTime;
rb.MovePosition(movePos);
anim.SetBool("isWalking", true);
Vector2 lookDir = mousePos - rb.position;
Debug.Log("Look dir is: " + lookDir);
Debug.Log("Rb pos is: " + rb.position);
float angle = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg - 90f;
rb.rotation = angle;
}
void SetAnimationState()
{
if (movement.x == 0 && movement.y == 0)
{
anim.SetBool("isWalking", false);
anim.SetBool("isRunning", false);
isRunning = false;
}
}
void handleRunningState()
{
if (isRunning == true)
{
anim.SetBool("isRunning", true);
moveSpeed = 30f;
} else
{
anim.SetBool("isRunning", false);
moveSpeed = 15f;
}
}
}
Comment