Reputation: 15
EDIT: The problem only occurs with the arrow keys, wasd keys work just fine, so I'm guessing the problem is my keyboard, but not completely sure.
I'm new to coding and to unity, so I'm trying to make a basic top down shooter game, but I'm having a problem with the movement, when I press up and right, if I press left and release the right key, the player keeps going right, as if I was pressing the right button. It doesn't happens the other way around, I don't know if the problem is in my movement code, in unity or in my keyboard. My movement script is as follows
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerMovement : MonoBehaviour
{
public float moveSpeed = 10f;
private float horizontalMove = 0f;
private float verticalMove = 0f;
public Rigidbody2D rb;
void Start()
{
}
void Update()
{
horizontalMove = Input.GetAxisRaw("Horizontal") * moveSpeed;
verticalMove = Input.GetAxisRaw("Vertical") * moveSpeed;
}
void FixedUpdate()
{
Vector2 moveDirection = new Vector2(horizontalMove, verticalMove);
rb.AddForce(moveDirection);
}
}
Upvotes: 1
Views: 647
Reputation: 562
It's because you are using rb.AddForce(moveDirection);
to move. Every fixed update if the key was pressed that line will add a force to the rigidbody; so it will repeatedly increase the force.
I assume that if you press the key and release it, the player still moves in that direction.
I suggest you to use another way to move the player. Like rb.velocity, it's easier to use, instead of AddForce, try:
rb.velocity = moveDirection;
Also, read the documentation of rb.AddForce.
Edit
Ok, so the problem may be the keyboard.
We now need to test if that it's true. Input.GetAxis
methods are configured in Edit > Project Settings > Input
, if the arrow keys are the problem, we should try with other keys. In the input menu find the Horizontal and Vertical Axes, and change the Positive Button
and Negative Button
for another key, and try again now with those keys.
You can read more about Axes Settings in the Input Manager documentation.
Upvotes: 1