Movement/Rotation Methods Don't Work Together
Hello everyone, I am very new to Unity and I am building a 2d top-down game. I have some code that allows me to point and click on the gameboard and have my player character walk towards the point at a constant speed while rotating to face the clicked location. To do this I call the following method "MoveClick" in Update:
void MoveClick()
{
bool RMB = Input.GetMouseButton(1);
if (RMB)
{
Vector3 clickPosition = Input.mousePosition;
clickPosition = Camera.main.ScreenToWorldPoint(clickPosition);
newPosition = new Vector3(clickPosition.x, clickPosition.y, transform.position.z);
moveDirection = newPosition - transform.position;
moveDirection.Normalize();
}
float targetAngle = Mathf.Atan2(moveDirection.y, moveDirection.x) * Mathf.Rad2Deg;
transform.rotation =
Quaternion.Slerp(transform.rotation,
Quaternion.Euler(0, 0, targetAngle),
clickRotation * Time.deltaTime);
transform.position = Vector3.MoveTowards(transform.position, newPosition, moveSpeed * Time.deltaTime);
}
My understanding is that by calling this in Update, it will check for a right mouse click and if so, will move the character to that point. So far this works great.
My issue is that since this is a shooter, I will want to shoot things. The way my character moves makes shooting very accurate, but not so much while the player is stationary. So I need to edit or add a method that allows me to turn my player character in the direction of a mouse click (left mouse click) in addition to the one that already turns and moves them on a right mouse click. To solve this problem I basically copied my above method and changed some variable names. This is what I wrote:
void RotateClick()
{
bool LMB = Input.GetMouseButton(0);
if (LMB)
{
Vector3 lclickPosition = Input.mousePosition;
lclickPosition = Camera.main.ScreenToWorldPoint(lclickPosition);
lookPosition = new Vector3(lclickPosition.x, lclickPosition.y, transform.position.z);
rotDirection = lookPosition - transform.position;
rotDirection.Normalize();
}
float targetRotation = Mathf.Atan2(rotDirection.y, rotDirection.x) * Mathf.Rad2Deg;
transform.rotation =
Quaternion.Slerp(transform.rotation,
Quaternion.Euler(0, 0, targetRotation),
clickRotation * Time.deltaTime);
}
Now, this also works well in Update. BUT ONLY WHEN I COMMENT OUT MY OTHER MOVEMENT METHOD. My update function looks like this:
void Update()
{
//MoveKeys();
MoveClick();
RotateClick();
}
Basically, the above code won't work properly if I call both MoveClick and RotateClick in Update, despite the fact that they each work just fine on their own. I encountered a similar issue with my method MoveKeys and have to keep it commented out. I've been stuck on this for several days now so any advice you guys have to give would be super appreciated!