- Home /
Question by
LordKitsune · Apr 25, 2018 at 06:02 AM ·
c#cameramovementplayer
Why are my player controls wierd.
Ok, so I want to make an FPS controller from scratch, i have camera movement down, and the asdw movement must be based on rotation of the object. It works sort of until I turn, then it goes in the opposite direction, what did I do wrong?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public static PlayerController instance;
private float playerMovementHorizontal;
private float playerMovementVertical;
public float walkSpeed = 30f;
public float sensitivyX = 2f;
public float sensitivyY = 2f;
private float yaw;
private float pitch;
private void Awake()
{
//cacheing instances to variables to save CPU cycles
instance = this;
}
private void movePlayer()
{
//moves player based on input put into Update()
Vector3 direction = transform.position - new Vector3(playerMovementHorizontal, 0f, playerMovementVertical);
direction = transform.TransformDirection(direction);
direction.Normalize();
direction.y = 0;
transform.Translate(direction);
}
private void rotateCamera()
{
//adjust the camera based on calculations made in update
transform.eulerAngles = new Vector3(pitch, yaw, 0f);
}
private void Update()
{
//calculates movement based on input from asdw keys or controller if one is plugged in
playerMovementHorizontal = Input.GetAxis("Horizontal") * Time.deltaTime * walkSpeed;
playerMovementVertical = Input.GetAxis("Vertical") * Time.deltaTime * walkSpeed;
//calculates Camera rotation according to mouse
pitch -= sensitivyY * Input.GetAxis("Mouse Y");
yaw += sensitivyX * Input.GetAxis("Mouse X");
}
private void FixedUpdate()
{
//used in FixedUpdate() as physic based movement should be done in Fixed
movePlayer();
rotateCamera();
}
}
Comment
You assign player$$anonymous$$ovementVertical to the z value of transform.position.
Answer by Captain_Pineapple · Apr 25, 2018 at 08:37 AM
I did not try it out but i guess you should be able to fix it by changing your move function to the following:
private void movePlayer()
{
//moves player based on input put into Update()
Vector3 direction = new Vector3(playerMovementHorizontal, 0f, playerMovementVertical);
direction.Normalize();
direction.y = 0;
transform.Translate(direction);
}
Since your direction should not be dependent of your current position. Also transform.translate should take care of the transformation of the direction. -> transform.tranlate scripting api