Ways to Unity 4: keyboard bindings for movements
Check your input system for a little bit
You just have to go to the Edit
-> Project Settings
-> Input Manager
-> Axis
.
Give it a look.
Done.
Let’s move our object with direction keys
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed = 10.0f;
public float turnSpeed = 2f;
public float forwardInput;
public float horizontalInput;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
forwardInput = Input.GetAxis("Vertical");
transform.Translate(Vector3.forward * Time.deltaTime * speed * forwardInput);
horizontalInput = Input.GetAxis("Horizontal");
transform.Translate(Vector3.right * Time.deltaTime * turnSpeed * horizontalInput);
}
}
Time.deltaTime
is the time difference between each frame of our game. The unit of it is second. We use it to simulate the real-world changes, to make our game more realistic.
Here is someone else’s explanation:
deltaTime
is the time in seconds that has passed since the last frame. So say you want an object to move 100 pixels(meters) in 1 second. You can determine the distance by multiplying 100 by the deltaTime.
Improve it with rotation
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private float speed = 10.0f;
private float turnSpeed = 40f;
private float forwardInput;
private float horizontalInput;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
forwardInput = Input.GetAxis("Vertical");
transform.Translate(Vector3.forward * Time.deltaTime * speed * forwardInput);
horizontalInput = Input.GetAxis("Horizontal");
//transform.Translate(Vector3.right * Time.deltaTime * turnSpeed * horizontalInput);
transform.Rotate(Vector3.up, Time.deltaTime * turnSpeed * horizontalInput);
}
}
Author
https://
ying
shaoxo.blogspot.com/2020/11/ways-to-unity-4-keyboard-bindings-for.html