Question by
DorTKOphir · Sep 15, 2019 at 09:10 PM ·
player movementtop down shooter
Trying my player to move in the direction of the mouse
Till now I have written this script:
public Camera cam;
public Rigidbody2D rb;
Vector2 mousePos;
bool isMoving = false;
float moveSpeed = 5f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
if (Input.GetKey(KeyCode.W))
{
isMoving = true;
}
else
{
isMoving = false;
}
}
private void FixedUpdate()
{
MovePlayer();
}
void MovePlayer()
{
Vector2 lookDir = mousePos - rb.position;
float angel = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg;
rb.rotation = angel - 80f;
if (isMoving)
{
Vector2 movement = new Vector2(lookDir.x / moveSpeed, lookDir.y / moveSpeed);
rb.MovePosition(rb.position + lookDir * moveSpeed * Time.fixedDeltaTime);
}
}
Its works, but the problem is that the speed of the player is getting bigger if the mouse is farther away from the player, and I dont want it to happend, I want the speed to be fixed. Pls help me, thank you
Comment
Your answer
Follow this Question
Related Questions
Rigidbody player movement doesn't response to gravity 0 Answers
Door disappearing problem Unity 5.3 3D. 1 Answer
seriously ANIMATOR 0 Answers
Camera spawn rotate with object 0 Answers
How to Apply Animation to Player 0 Answers