- Home /
third person controller like in Assasian's creed or GTA5
Hello unity community i am trying to make a third person game where the player moves like in assasians creed. I am making somewhere in my code logic a mistake and i have spend 73h trying to fix my code. My character keeps rotating in funny ways. For now i have character with a sphere attached like child object and in the sphere the main camera. The sphere acts like axis where the camera rotates around the player and its positioned in the middle of the character. What i am trying to do is: 1. Free look while not pressing WSAD around the player. 2. When i press W the character should rotate to where the camera is facing and start walking 3. If i press A/S/D the character should walk left backwards and right without camera moving to its walking direction Here is my code for now
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class mouseLook : MonoBehaviour
{
public float mouseSpeed = 100f;
public Transform camOrbit; //sphere inside the player
public Transform playerBody; //player
float xRotation = 0f;
float yRotation = 0f;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
//Cursor.visible = false;
}
void Update()
{
float mouseX = Input.GetAxis("Mouse X") * mouseSpeed * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSpeed * Time.deltaTime;
xRotation -= mouseY;
xRotationPlayer -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
yRotation += mouseX;
yRotationPlayer += mouseX;
camOrbit.transform.localRotation = Quaternion.Euler(xRotation, yRotation, 0f);
if (Input.GetKeyDown(KeyCode.W))
{
playerBody.transform.localRotation = Quaternion.Euler(0f, yRotationPlayer, 0f);
}
if (Input.GetKey(KeyCode.W))
{
playerBody.transform.localRotation = Quaternion.Euler(0f, yRotationPlayer, 0f);
camOrbit.transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
}
if (Input.GetKeyUp(KeyCode.W))
{
yRotation = 0f;
}
if (Input.GetKey(KeyCode.A))
{
playerBody.transform.localRotation = Quaternion.Euler(0f, -90f, 0f);
}
if (Input.GetKey(KeyCode.D))
{
playerBody.transform.localRotation = Quaternion.Euler(0f, 90f, 0f); ;
}
if (Input.GetKey(KeyCode.A))
{
playerBody.transform.localRotation = Quaternion.Euler(0f, 0f, 0f);
}
}
}
Your answer
Follow this Question
Related Questions
More specific Quaternion.LookRotation 1 Answer
Instantiating blood on walls using gameobject 1 Answer
Confused with LookRotation in C# 1 Answer
Make Third Person Character Rotate 1 Answer