- Home /
Movement correct to wasd Help
Hey!
I am a begginer and I downloaded THIS character movement, But I'd like it to move by keys wasd. Please, can you give me an advice? Or screenshot how to change it in script?
Thank you for any help!
Answer by AmanKarowalia · Mar 27, 2017 at 07:42 AM
@Mimmy21 this works but add this to the character component, and make sure to configure the speed through inspector under the script name. This works for arrow keys though, not sure about WASD.
using UnityEngine; using System.Collections;
public class PlayerController : MonoBehaviour {
private Rigidbody rb;
public float speed;
void Start () {
rb = GetComponent<Rigidbody> ();
}
void FixedUpdate () {
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
rb.AddForce (movement * speed);
}
}
Answer by SohailBukhari · Mar 27, 2017 at 08:03 AM
you can use the Input Axis in Unity to control movement on how to play or stop an animation based on the current value of an axis. You can use the Input manager (Edit > Project Settings > Input) to configure the control keys however you like. You can set the W key to be a button for the positive direction of the axis called Vertical. It is already configured that way by default.
Now, in scripting, you can read the value of the Vertical axis using the Input.GetAxis Method to get the walk speed
public class Movement:MonoBehaviour
{
[SerializeField] private float _maxwalkSpeed = 5.0f;
[SerializeField]private float _maxTurnSpeed = 10.0f;
[SerializeField] private Animation animation;
private void Update()
{
var walkSpeed = Input.GetAxis("Vertical")*_maxwalkSpeed;
var turnSpeed = Input.GetAxis("Horizontal")*_maxTurnSpeed;
this.transform.Translate(0,0,walkSpeed*Time.deltaTime);
this.transform.Rotate(0, turnSpeed * Time.deltaTime,0);
if (walkSpeed > 3)
{
if (animation == null) return;
animation.Play("Walk");
}
else
{
if (animation == null) return;
animation.Stop("Walk");
}
}
}
Your answer
Follow this Question
Related Questions
how to make 2d character jump? 0 Answers
How do I prevent my fps player from flying? 1 Answer
Help please in regards to character controller 0 Answers
Modified CharacterController.Move script not working 1 Answer
How to create an eight point 3d character controller in unity with rigidbody enabled 0 Answers