- Home /
Question by
mohamedalryanwd · Nov 08, 2021 at 08:12 PM ·
unity 5camerarotation3dcharactercontroller
player rotate to camera direction but not moving in it's direction
So i have the character that moves Horizontal and vertical + it's facing the camera direction, although when i start moving it doesn't move in the camera direction no matter where i look. sorry if it sound like a stupid question i'm still newbie here :)
[SerializeField] float archerSpeed = 3f;
[SerializeField] float archerSprintSpeed = 6f;
[SerializeField] float jumpHeight = 1f;
[SerializeField] float smooth = 5f;
[SerializeField] float tiltAngle = 60f;
float gravityValue = -9.81f;
bool groundedPlayer;
// Refrences
CharacterController characterController;
Vector3 playerVelocity;
Animator anim;
private void Start()
{
transform.rotation = Quaternion.LookRotation(Camera.main.transform.forward, Camera.main.transform.up);
characterController = GetComponent<CharacterController>();
anim = GetComponent<Animator>();
}
private void Update()
{
anim.SetFloat("Speed", 0f);
GroundedPlayer();
ArcherMoves();
ArcherSprint();
//ArcherJump();
ArcherRotation();
}
private void ArcherRotation()
{
float tiltAroundZ = Input.GetAxis("Horizontal") * tiltAngle;
float tiltAroundX = Input.GetAxis("Vertical") * tiltAngle;
transform.Translate(Vector3.forward.normalized * archerSpeed);
Quaternion target = Quaternion.Euler(tiltAroundX, 0, tiltAroundZ);
transform.rotation = Quaternion.Slerp(transform.localRotation, target, Time.deltaTime * smooth);
}
private void GroundedPlayer()
{
if(groundedPlayer && playerVelocity.y <0)
{
playerVelocity.y = 0f;
}
playerVelocity.y += gravityValue * Time.deltaTime;
characterController.Move(playerVelocity * Time.deltaTime);
}
private void ArcherMoves()
{
transform.localEulerAngles = new Vector3(transform.localEulerAngles.x, Camera.main.transform.localEulerAngles.y, transform.localEulerAngles.z);
Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
characterController.Move(move * archerSpeed * Time.deltaTime);
if (move != Vector3.zero)
{
anim.SetFloat("Speed", 0.5f);
gameObject.transform.forward = move * archerSpeed;
}
}
private void ArcherSprint()
{
Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
characterController.Move(move * archerSprintSpeed * Time.deltaTime);
if (move != Vector3.zero && Input.GetKey(KeyCode.LeftShift))
{
anim.SetFloat("Speed", 1f);
gameObject.transform.forward = move;
print("Sprinting");
}
}
private void ArcherJump()
{
if(Input.GetKeyDown(KeyCode.Space) && groundedPlayer)
{
playerVelocity.y += Mathf.Sqrt(jumpHeight * -3f * gravityValue);
print("Jumping");
}
}
Comment
Your answer
Follow this Question
Related Questions
Rotate camera only in 2 directions based on player touch 1 Answer
Camera lock on enemy 0 Answers
make AI shoot at incoming bullet 2 Answers
Rotating Player with Mouse 0 Answers
Smooth rotation to child object 1 Answer