first person movement in unity code example
Example 1: fps movment unity
public float walkSpeed = 6.0F;
public float jumpSpeed = 8.0F;
public float runSpeed = 8.0F;
public float gravity = 20.0F;
private Vector3 moveDirection = Vector3.zero;
private CharacterController controller;
void Start()
{
controller = GetComponent<CharacterController>();
}
void Update()
{
if (controller.isGrounded)
{
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= walkSpeed;
if (Input.GetButton("Jump"))
moveDirection.y = jumpSpeed;
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
Example 2: first person view unity
public Transform followTarget;
public Vector3 targetOffset;
public float moveSpeed = 2f;
private Transform myTransform;
void Start(){
myTransform = transform;
}
public void SetTarget(Transfrom aTransform){
followTarget = aTransform;
}
void LateUpdate(){
if(followTarget != null){
myTransform.position = Vector3.Lerp(myTransform.position, followTarget.position + targetOffset, moveSpeed * Time.deltaTime);
}
}