2D topdown: mouse rotation and shooting,2D top down: mouse rotation and shooting
I have the following code to be able to move the player while rotate it with the mouse.
void Update() {
movement.x = Input.GetAxisRaw("Horizontal");
movement.y = Input.GetAxisRaw("Vertical");
mouse = camera.ScreenToWorldPoint(Input.mousePosition);
if (Input.GetKey(KeyCode.Mouse0)) {
Debug.Log("Fire");
// Shoot();
}
}
void FixedUpdate() {
rb.MovePosition(rb.position + movement * speed * Time.fixedDeltaTime);
Vector2 lookDirection = mouse - rb.position;
float angle = Mathf.Atan2(lookDirection.y, lookDirection.x) * Mathf.Rad2Deg;
rb.rotation = angle;
}
This works as intended; however, the problem comes when you are trying to fire while the player is moving. In that case the Fire is never registered, you never see the "Fire" in the console and it acts as if you are not clicking.
I tried replacing the Mouse button with the space bar to fire and it seems to work fine. So its clearly a problem between the mouse being used to rotate and also trying to fire. But I dont know, everybody seems to be doing it this way so I am out of ideas.
Answer by wastifaiq · Jan 09 at 10:18 AM
Wow... I have been looking at this for a while and I genuinely don't see any mistake here... It's not like you if statement is dependant on any of the other codes. Try this for a test tho. Try removing the code for movement. And just have it constantly moving without input then tell the result of this experimant.