So Im making A FPS game from scratch in unity , I got my player to look around but I cant get the moving part .
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
//Variables
public float mousesens = 3f;
public float keyboarsens = 5f;
public float Xm;
public float Ym;
public float Xr;
Vector3 Movex;
Vector3 Movey;
Vector3 MouseLook;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Ym = Input.GetAxisRaw ("Vertical");
Xm = Input.GetAxisRaw ("Horizontal");
Xr = Input.GetAxisRaw ("Mouse X");
Movex = new Vector3 (keyboarsens * Xm * Time.deltaTime, 0, 0) ;
Movey = new Vector3 (0, 0, keyboarsens * Ym * Time.deltaTime) ;
transform.Rotate (0,Xr * mousesens, 0);
transform.localPosition += Movex + Movey ;
}
}
this is my code and player moves along world x ,y ,z axis but not on its own axis I tried using transform.translate but its the same is there any way to move it along its axis ?
try using transform.position instead of transform.localPosition
@CrazyLule:
Use transform.TransformDirection(Vector3 direction) and it will transform the direction you’re facing from local space into world space:
void Update () {
Ym = Input.GetAxisRaw ("Vertical");
Xm = Input.GetAxisRaw ("Horizontal");
Xr = Input.GetAxisRaw ("Mouse X");
Movex = new Vector3 (keyboarsens * Xm * Time.deltaTime, 0, 0) ;
Movey = new Vector3 (0, 0, keyboarsens * Ym * Time.deltaTime) ;
Vector3 movement = Movex+Movey;
//following line lets him walk into the direction he's facing
movement = transform.TransformDirection (movement);
transform.Rotate(0,Xr * mousesens, 0);
transform.position += movement ;
}
If your script is attached to the player, get the transform.forward
, transform.right
and tranform.up
vectors. These vectors are the local forward, local right and local up directions of the object.
Ym = Input.GetAxisRaw ("Vertical");
Xm = Input.GetAxisRaw ("Horizontal");
// Here, you are getting the players forward direction and multiplying it by the speed and the Xm, which is 0 if you're not pressing anything (so the player wouldn't move on that axis)
Movex = tranform.right * Xm * keyboardsens * Time.deltaTime ;
// Same thing happens here. If you want the player to move upwards (e.g. you're making a 2d game), use transform.up here.
Movey = tranform.forward * Ym * keyboardsens * Time.deltaTime ;
transform.Rotate (0,Xr * mousesens, 0);
transform.localPosition += Movex + Movey ;
I could put up some visuals, if you need to understand this all a bit better.