Showing posts with label Movement. Show all posts
Showing posts with label Movement. Show all posts

Understanding Mathf functions - Lerp, MoveTowards, PingPong | Diff | Mathf | Unity | @Unity3DSchool


TestScript.cs
using UnityEngine;
using UnityEngine.UI;

public class TestScript : MonoBehaviour
{
    public Slider lerpSlider;
    public Slider moveTowardsSlider;
    public Slider pingPongSlider;

    void Update()
    {
        //Lerp
        lerpSlider.value = Mathf.Lerp(lerpSlider.value, lerpSlider.maxValue, 0.5f * Time.deltaTime);
        //MoveTowards
        moveTowardsSlider.value = Mathf.MoveTowards(moveTowardsSlider.value, moveTowardsSlider.maxValue, 10f * Time.deltaTime);
        //PingPong
        pingPongSlider.value = Mathf.PingPong(20 * Time.time, pingPongSlider.maxValue);
    }
}

Player Movement using Character Controller(Move, Turn, Jump, Fall) | Unity Game Engine


PlayerController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(CharacterController))]
public class PlayerController : MonoBehaviour
{
    public float speed = 3;
    public float rotationSpeed = 90;
    public float gravity = -20f;
    public float jumpSpeed = 15;

    CharacterController characterController;
    Vector3 moveVelocity;
    Vector3 turnVelocity;

    void Awake()
    {
        characterController = GetComponent<CharacterController>();
    }

    void Update()
    {
        var hInput = Input.GetAxis("Horizontal");
        var vInput = Input.GetAxis("Vertical");

        if(characterController.isGrounded)
        {
            moveVelocity = transform.forward * speed * vInput;
            turnVelocity = transform.up * rotationSpeed * hInput;
            if(Input.GetButtonDown("Jump"))
            {
                moveVelocity.y = jumpSpeed;
            }
        }
        //Adding gravity
        moveVelocity.y += gravity * Time.deltaTime;
        characterController.Move(moveVelocity * Time.deltaTime);
        transform.Rotate(turnVelocity * Time.deltaTime);
    }
}

Character movement via on-screen Joystick controller input | Rigidbody | Unity Game Engine


JoystickController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class JoystickController : MonoBehaviour, IPointerDownHandler, IDragHandler, IPointerUpHandler
{
    [SerializeField]
    private float maxDisplacement = 200;
    Vector2 startPos;
    Transform handle;

    public static float Horizontal = 0, Vertical = 0;

    void Start()
    {
        handle = transform.GetChild(0);
        startPos = handle.position;
    }

    void UpdateHandlePosition(Vector2 pos)
    {
        var delta = pos - startPos;
        delta = Vector2.ClampMagnitude(delta, maxDisplacement);
        handle.position = startPos + delta;
        Horizontal = delta.x / maxDisplacement;
        Vertical = delta.y / maxDisplacement;
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        UpdateHandlePosition(eventData.position);
    }

    public void OnDrag(PointerEventData eventData)
    {
        UpdateHandlePosition(eventData.position);
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        UpdateHandlePosition(startPos);
    }
}

JoystickMove.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(Rigidbody))]
public class JoystickMove : MonoBehaviour
{
    public float speed = 5;
    Rigidbody rigidBody;

    void Awake()
    {
        rigidBody = GetComponent<Rigidbody>();
    }

    void FixedUpdate()
    {
        float inputH = JoystickController.Horizontal;
        float inputV = JoystickController.Vertical;
        rigidBody.velocity = new Vector3(inputH * speed, rigidBody.velocity.y, inputV * speed);
    }
}

Character movement via on-screen touch controller input | Rigidbody | Unity Game Engine


TouchController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class TouchController : MonoBehaviour
{
    public static float Horizontal = 0, Vertical = 0;

    void Awake()
    {
        SetupButton(transform.Find("up").gameObject, Vector2.up);
        SetupButton(transform.Find("down").gameObject, Vector2.down);
        SetupButton(transform.Find("left").gameObject, Vector2.left);
        SetupButton(transform.Find("right").gameObject, Vector2.right);
    }

    void SetupButton(GameObject buttonObject, Vector2 position)
    {
        EventTrigger eventTrigger = buttonObject.AddComponent<EventTrigger>();

        var pointerDown = new EventTrigger.Entry();
        pointerDown.eventID = EventTriggerType.PointerDown;
        pointerDown.callback.AddListener((e) => UpdateAxisValue(position));
        eventTrigger.triggers.Add(pointerDown);

        var pointerUp = new EventTrigger.Entry();
        pointerUp.eventID = EventTriggerType.PointerUp;
        pointerUp.callback.AddListener((e) => UpdateAxisValue(position, reset: true));
        eventTrigger.triggers.Add(pointerUp);
    }

    void UpdateAxisValue(Vector2 position, bool reset = false)
    {
        if (position.x == 0)
            Vertical = reset ? 0 : position.y;
        else
            Horizontal = reset ? 0 : position.x;
    }
}

TouchMove.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(Rigidbody))]
public class TouchMove : MonoBehaviour
{
    public float speed = 5;
    Rigidbody rigidBody;

    void Awake()
    {
        rigidBody = GetComponent<Rigidbody>();
    }

    void FixedUpdate()
    {
        float inputH = TouchController.Horizontal;
        float inputV = TouchController.Vertical;
        rigidBody.velocity = new Vector3(inputH * speed, rigidBody.velocity.y, inputV * speed);
    }
}

Character movement via keyboard/controller input | Rigidbody | Unity Game Engine


Move.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(Rigidbody))]
public class Move : MonoBehaviour
{
    public float speed = 5;
    Rigidbody rigidBody;

    void Awake()
    {
        rigidBody = GetComponent<Rigidbody>();
    }

    void FixedUpdate()
    {
        float inputH = Input.GetAxis("Horizontal");
        float inputV = Input.GetAxis("Vertical");
        rigidBody.velocity = new Vector3(inputH * speed, rigidBody.velocity.y, inputV * speed);
    }
}

Double Jump | Rigidbody | Unity Game Engine


DoubleJump.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(Rigidbody))]
public class DoubleJump : MonoBehaviour
{
    public float jumpForce = 5;
    public float groundDistance = 0.5f;

    Rigidbody rigidBody;
    bool canDoubleJump;

    void Awake()
    {
        rigidBody = GetComponent<Rigidbody>();
    }

    bool IsGrounded()
    {
        return Physics.Raycast(transform.position, Vector3.down, groundDistance);
    }

    void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            if(IsGrounded())
            {
                rigidBody.velocity = Vector3.up * jumpForce;
                canDoubleJump = true;
            }
            else if(canDoubleJump)
            {
                rigidBody.velocity = Vector3.up * jumpForce;
                canDoubleJump = false;
            }
        }
    }
}

Single Jump | Rigidbody | Unity Game Engine


SingleJump.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(Rigidbody))]
public class SingleJump : MonoBehaviour
{
    public float jumpForce = 5;
    public float groundDistance = 0.5f;

    Rigidbody rigidBody;

    void Awake()
    {
        rigidBody = GetComponent<Rigidbody>();
    }

    bool IsGrounded()
    {
        return Physics.Raycast(transform.position, Vector3.down, groundDistance);
    }

    void Update()
    {
        if(Input.GetMouseButtonDown(0) && IsGrounded())
        {
            rigidBody.velocity = Vector3.up * jumpForce;
        }
    }
}

Continuous Jump | Rigidbody | Unity Game Engine


Jump.cs
using UnityEngine;

[RequireComponent(typeof(Rigidbody))]
public class Jump : MonoBehaviour
{
    public float jumpForce = 4;
    public float jumpInterval = 0.25f;

    Rigidbody rigidBody;
    float jumpTimer;

    void Awake()
    {
        rigidBody = GetComponent<Rigidbody>();
    }

    void Update()
    {
        jumpTimer += Time.deltaTime;
        if (Input.GetMouseButtonDown(0))
        {
            if (jumpTimer > jumpInterval)
            {
                jumpTimer = 0;
                rigidBody.velocity = Vector3.up * jumpForce;
            }
        }
    }
}

Patrolling Between two points


Patrolling.cs
using System.Collections;
using UnityEngine;

public class Patrolling : MonoBehaviour
{
    public float speed = 5;
    public Transform point1;
    public Transform point2;

    IEnumerator Start()
    {
        Transform target = point1;
        while (true)
        {
            transform.position = Vector3.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
            if (Vector3.Distance(transform.position, target.position) <= 0)
            {
                target = target == point1 ? point2 : point1;
                yield return new WaitForSeconds(0.5f);
            }
            yield return null;
        }
    }
}

Avoiding Obstacles While Moving to a Point Using NavMesh


NavMeshPointMovement.cs
using UnityEngine;
using UnityEngine.AI;

public class NavMeshPointMovement : MonoBehaviour
{
    NavMeshAgent agent;
    RaycastHit hit;

    void Awake()
    {
        agent = GetComponent<NavMeshAgent>();
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 100, LayerMask.GetMask("Ground")))
            {
                agent.SetDestination(hit.point);
            }
        }
    }
}

Moving Player through Collection of Clicked Points on a Surface


ClickedPointsMovement.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ClickedPointsMovement : MonoBehaviour
{
    public float speed = 15;
    Queue<Vector3> targetPointsQueue = new Queue<Vector3>();
    RaycastHit hit;
    Camera mainCam;
    Coroutine _MoveCR;
    int layerMask;

    void Awake()
    {
        mainCam = Camera.main;
        layerMask = LayerMask.GetMask("Ground");
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            if (Physics.Raycast(mainCam.ScreenPointToRay(Input.mousePosition), out hit, 100, layerMask))
            {
                targetPointsQueue.Enqueue(hit.point);
                if (_MoveCR == null)
                {
                    _MoveCR = StartCoroutine(MoveThroughPoints(targetPointsQueue));
                }
            }
        }
    }

    IEnumerator MoveThroughPoints(Queue<Vector3> points)
    {
        while (points.Count > 0)
        {
            Vector3 targetPoint = points.Dequeue();
            targetPoint = new Vector3(targetPoint.x, transform.position.y, targetPoint.z);
            while (Vector3.Distance(transform.position, targetPoint) > 0.01f)
            {
                transform.position = Vector3.MoveTowards(transform.position, targetPoint, speed * Time.deltaTime);
                yield return null;
            }
        }
        _MoveCR = null;
    }
}

Moving Player to a Point Clicked by the Mouse on a Surface


ClickedPointMovement.cs
using System.Collections;
using UnityEngine;

public class ClickedPointMovement : MonoBehaviour
{
    public float speed = 30;
    RaycastHit hit;
    Camera mainCam;
    Coroutine _MoveCR;
    int layerMask;

    void Awake()
    {
        mainCam = Camera.main;
        layerMask = LayerMask.GetMask("Ground");
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            if (Physics.Raycast(mainCam.ScreenPointToRay(Input.mousePosition), out hit, 100, layerMask))
            {
                if(_MoveCR != null)
                {
                    StopCoroutine(_MoveCR);
                }
                _MoveCR = StartCoroutine(MoveToPosition(hit.point));
            }
        }
    }

    IEnumerator MoveToPosition(Vector3 targetPoint)
    {
        targetPoint = new Vector3(targetPoint.x, transform.position.y, targetPoint.z);
        while (Vector3.Distance(transform.position, targetPoint) > 0.01f)
        {
            transform.position = Vector3.MoveTowards(transform.position, targetPoint, speed * Time.deltaTime);
            yield return null;
        }
    }
}

Player movement using character controller based on front facing direction

PlayerMovement.cs
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    CharacterController characterController;

    public float speed = 5;
    public float turnSpeed = 90;

    void Awake()
    {
        characterController = GetComponent<CharacterController>();
    }

    void Update()
    {
        characterController.Move(transform.forward * Input.GetAxis("Vertical") * speed * Time.deltaTime);
        transform.Rotate(Vector3.up, Input.GetAxis("Horizontal") * turnSpeed * Time.deltaTime);
    }
}

Player simple movement based on input direction

PlayerSimpleMovement.cs
using UnityEngine;

public class PlayerSimpleMovement : MonoBehaviour
{
    float h = 0;
    float v = 0;
    public float speed = 5;

    void Update()
    {
        h = Input.GetAxis("Horizontal");
        v = Input.GetAxis("Vertical");

        transform.position += new Vector3(h * Time.deltaTime * speed, 0, v * Time.deltaTime * speed);
    }
}