- Home /
WASD Controls not in-sync with camera?
I'm making a game with a first-person view, and I decided not to use the prefab first-person controller and try to create it all from scratch. I finally got the camera to move when I move the mouse, but the WASD controls don't seem to be correct. I can go forward, backward, and sideways with WASD but in many games they change with the camera. In the game for example, when I first start up and go forward with the W/forward-arrow key, and I turn the camera in the opposite direction, I can't use W to go into that direction. I have to use the S key to go back. This is the same with all directions. I just need to know what function I need so that the direction I'm facing with the camera, the controls become oriented with that direction. I've been looking, I'm not sure if there are any other up-to-date questions about this.
using UnityEngine;
using System.Collections;
public class WalkScript : MonoBehaviour {
private Transform player;
public float speed = 6.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
private Vector3 moveDirection = Vector3.zero;
float xAxisValue = Input.GetAxis("Horizontal");
float zAxisValue = Input.GetAxis("Vertical");
void Update()
{
CharacterController controller = GetComponent<CharacterController>();
if (controller.isGrounded)
{
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
if (Input.GetButton("Jump"))
moveDirection.y = jumpSpeed;
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
}
You should post your code along with your question. That would give us a better idea of what you are doing and help us figure out why it's not doing what you want it to.
Anyway, you said you're already rotating the camera as the mouse moves, but are you also rotating the player? The player is probably moving in the direction it is facing and not the direction the camera is facing.
I'm sorry that I didn't reply yesterday. I'm completely new to this, I have had no knowledge whatsoever with C# before so I've been using tutorials. I will add the script to the question.
Answer by DiGiaCom-Tech · May 28, 2016 at 07:45 PM
@Hunter4408 ... Is the Camera a child of the Player? If it is NOT then you must write code to update the Camera's position/rotation so that it follows the Player as you intend. The easiest solution is to place the Camer as a child of the Player and set it's position/rotation relative to the Player as you like (i.e. looking at the Player's back for 3rd person or inside the Player's head for 1st person). This way it becomes part of the Player and as the Player moves and turns the Camera moves and turns in sync.
I'm 99.9% sure the camera is a child of the player, and they are both aligned. If you mean that I have to hit a tab to see the Camera on the hierarchy, then it is a part of the Player.