Reputation: 141
Since yesterday I started working on a 2D game, and I found a problem when I was making the character movement. I wanted to make the character move left, right, up and down and since I was having a hardtime using the new Unity's Input System, I used the old Input.GetAxis(). My character was moving but I didn't like the smooth movement, I wanted the player to always move at the same speed and to stop in the moment that I released the movement keys. But know I can only make him move a bit everytime I press the keys.
Here's the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AlternativeController : MonoBehaviour
{
public float speed;
bool canMove = true;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (canMove)
{
Move();
}
}
void Move()
{
if (Input.GetKeyDown("right"))
{
transform.Translate(speed, 0, 0);
}
if (Input.GetKeyDown("left"))
{
transform.Translate(-speed, 0, 0);
}
if (Input.GetKeyDown("up"))
{
transform.Translate(0, speed, 0);
}
if (Input.GetKeyDown("down"))
{
transform.Translate(0, -speed, 0);
}
}
}
Upvotes: 1
Views: 647
Reputation: 2946
You can use:
Input.GetAxisRaw("Horizontal"); Input.GetAxisRaw("Vertical");
This will use the more portable GetAxis
of the old input system, without the smoothing of GetAxis()
.
Alternatively, as said in the comments, you can replace Input.GetKeyDown()
with Input.GetKey()
to check if a key is being held.
Upvotes: 2