Answers for "hoq to add movement in unity"

C#
0

hoq to add movement in unity

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class personMovement : MonoBehaviour
{
	//This is for Third Person Movement btw
    //use main camera as cam

    public Rigidbody rb;
    public Vector3 jump;
    public float jumpForce = 2.0f;
    public bool isGrounded;
    public CharacterController controller;
    public Transform cam;
    public float speed = 6f;
    public float turnSmoothTime = 0.1f;
    float turnSmoothVelocity;


     void Start(){
        rb = GetComponent<Rigidbody>();
        jump = new Vector3(0.0f, 2.0f, 0.0f);
    }
    void OnCollisionStay(){
        isGrounded = true;
    }

    // Update is called once per frame
    void Update()
    {
        float horizontal = Input.GetAxisRaw("Horizontal");
        float vertical = Input.GetAxisRaw("Vertical");
        Vector3 direction = new Vector3(horizontal ,0f ,vertical);

        if(direction.magnitude >= 0.1f)
        {
            float targetAngle = Mathf.Atan2(direction.x , direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
            float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y , targetAngle , ref turnSmoothVelocity , turnSmoothTime);
            transform.rotation = Quaternion.Euler(0f , angle , 0f);

            Vector3 moveDir = Quaternion.Euler(0f,targetAngle,0f) * Vector3.forward;
            controller.Move(moveDir * speed * Time.deltaTime);
        }
        if(Input.GetKeyDown(KeyCode.Space) && isGrounded){

            rb.AddForce(jump * jumpForce, ForceMode.Impulse);
            isGrounded = false;
        }
    }
}
Posted by: Guest on August-01-2021

C# Answers by Framework

Browse Popular Code Answers by Language