- Home /
Moving a character depending on the direction he is facing (C#/Unity3D)
Right now I have a small soldier on the screen that moves with W, A, S, D and rotates / changes direction with the arrow keys. What I want to happen is when the player's direction changes (by using the arrow keys), pushing W will send him in that direction instead of up the screen.
Also (for example), if you are holding D and the right arrow key at the same time he should move in a circle about a point on the ground (instead of spinning in a circle while moving in a straight line to the right).
Here is my current code:
public class MovePlayer : MonoBehaviour {
void Update() {
// Rotate left
if (Input.GetKey (KeyCode.LeftArrow)) {
transform.Rotate(0, 0, 1.3f);
}
// Rotate right
if (Input.GetKey(KeyCode.RightArrow)) {
transform.Rotate(0, 0, -1.3f);
}
// Strafe left
if (Input.GetKey (KeyCode.A)) {
Vector3 position = this.transform.position;
position.x -= 0.055f;
this.transform.position = position;
}
// Move up
if (Input.GetKey (KeyCode.W)) {
Vector3 position = this.transform.position;
position.y += 0.043f;
this.transform.position = position;
}
// Move down
if (Input.GetKey (KeyCode.S)) {
Vector3 position = this.transform.position;
position.y -= 0.043f;
this.transform.position = position;
isMoving = true;
}
// Strafe right
if (Input.GetKey (KeyCode.D)) {
Vector3 position = this.transform.position;
position.x += 0.055f;
this.transform.position = position;
}
}
}
Any ideas? Wasn't sure what to search exactly.
Answer by Onk3y · Aug 05, 2017 at 06:29 PM
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class movePlayer : MonoBehaviour {
public float moveSpeed = 15f;
public float turnSpeed = 200f;
void Update () {
transform.position += transform.forward * Input.GetAxis("Vertical") * moveSpeed * Time.deltaTime;
transform.position+= transform.right* Input.GetAxis("Horizontal") * moveSpeed * Time.deltaTime;
transform.Rotate(Vector3.up * Input.GetAxis("Another Horizontal") * turnSpeed * Time.deltaTime);
}
}
This is probably the easiest way of doing this. Hit me up if you have any questions ;)
Your answer
![](https://koobas.hobune.stream/wayback/20220613195823im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Need help with launching mechanic 0 Answers
Im trying to create a word game with a twist 0 Answers
Leaning/peeking 1 Answer
How does Unity3d uses nvidia 0 Answers