Question by
abhinav0298 · Jan 27 at 11:35 AM ·
scripting beginneruntiy3d
Whenever i try to rotate my character it snaps back to its normal positoin
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PlayerMovement1 : MonoBehaviour { //Varaibles [SerializeField] private float MoveSpeed; [SerializeField] private float WalkSpeed; [SerializeField] private float RunSpeed;
private Vector3 MoveDirection;
private Vector3 velocity;
[SerializeField] private bool isGrounded;
[SerializeField] private LayerMask GroundMask;
[SerializeField] private float GroundCheckDistance;
[SerializeField] private float gravity;
[SerializeField] private float JumpHeight;
//References
private CharacterController controller;
private Animator animator;
private void Start()
{
controller = GetComponent<CharacterController>();
animator = GetComponentInChildren<Animator>();
}
private void Update()
{
Move();
}
public void Move()
{
isGrounded = Physics.CheckSphere(transform.position, GroundCheckDistance, GroundMask);
if (isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
float MoveZ = Input.GetAxisRaw("Vertical");
float MoveX = Input.GetAxisRaw("Horizontal");
MoveDirection = new Vector3(MoveX, 0, MoveZ).normalized;
MoveDirection = transform.TransformDirection(MoveDirection);
if (isGrounded)
{
if (MoveDirection != Vector3.zero && !Input.GetKey(KeyCode.LeftShift))
{
//Walk
walk();
}
else if (MoveDirection != Vector3.zero && Input.GetKey(KeyCode.LeftShift))
{
//Run
run();
}
else if (MoveDirection == Vector3.zero)
{
//idle
idle();
}
if (Input.GetKeyDown(KeyCode.Space))
{
jump();
}
MoveDirection *= MoveSpeed;
}
float targetAngle = Mathf.Atan2(MoveDirection.x, MoveDirection.z)*Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f,targetAngle,0);
controller.Move(MoveDirection * Time.deltaTime);
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
private void walk()
{
MoveSpeed = WalkSpeed;
animator.SetFloat("Speed", 0.5f, 0.1f, Time.deltaTime);
}
private void run()
{
MoveSpeed = RunSpeed;
animator.SetFloat("Speed", 1, 0.1f, Time.deltaTime);
}
private void idle()
{
animator.SetFloat("Speed", 0,0.1f,Time.deltaTime);
}
private void jump()
{
velocity.y = Mathf.Sqrt(JumpHeight * -2 * gravity);
}
}
Comment
Your answer
Follow this Question
Related Questions
Trigger script function from ARKit UnityARUtility class 0 Answers
Floating scifi display to show results from database query 0 Answers
Having some doubts on the basics of scripting,A little doubt about some terminology 0 Answers
Adding prefab objects to a list on another script and object? 2 Answers
How do i find out if teleport was unsuccessful? (VR VIVE) 0 Answers