Search Unity

I am curious about the character physics movement. SomeBody Help me.

Discussion in 'Physics' started by rlaghco276, May 21, 2019.

  1. rlaghco276

    rlaghco276

    Joined:
    Apr 12, 2019
    Posts:
    8
    Hello, i'm producing in 3d environment.

    There is a character on the plane.

    I want to make the character move when I click.

    So I created a C # script.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5.  
    6. public class PlayerMoving : MonoBehaviour
    7. {
    8.     Vector3 _targetPosition;
    9.     Vector3 _lookAtTarget;
    10.     Quaternion _playerRot;
    11.     public float RotSpeed = 3f;
    12.     public Animator WalkingAnimator;
    13.  
    14.     void Start()
    15.     {
    16.         WalkingAnimator = GetComponent<Animator>();
    17.     }
    18.     void Update()
    19.     {
    20.         if (_targetPosition.y != 0)
    21.             _targetPosition.y = 0;
    22.         if (Input.GetMouseButtonUp(0))
    23.         {
    24.             SetTargetPosition();
    25.         }
    26.         if (WalkingAnimator)
    27.             Move();
    28.     }
    29.     void SetTargetPosition()
    30.     {
    31.         Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    32.         RaycastHit hit;
    33.  
    34.         if (Physics.Raycast(ray, out hit, 1000))
    35.         {
    36.             _targetPosition = hit.point;
    37.             _lookAtTarget = new Vector3(_targetPosition.x - transform.position.x, transform.position.y,
    38.                 _targetPosition.z - transform.position.z);
    39.             _playerRot = Quaternion.LookRotation(_lookAtTarget);
    40.             WalkingAnimator.SetBool("Walking", true);
    41.         }
    42.     }
    43.     void Move()
    44.     {
    45.         transform.rotation = Quaternion.Slerp(transform.rotation, _playerRot, RotSpeed * Time.deltaTime);
    46.         transform.position = Vector3.MoveTowards(transform.position, _targetPosition, RotSpeed * Time.deltaTime);
    47.         if (transform.position == _targetPosition)
    48.         {
    49.             WalkingAnimator.SetBool("Walking", false);
    50.         }
    51.     }  
    52. }
    53.  
    It works fine. By the way, if a character moves in the z-axis, the character's box call rider loses it freely.

    And when the character moves diagonally, he leans at 45 degrees. Axis can not be fixed.

    In Rigidbody, Is Kinematic, Interpolate, Discrete, Freeze (Position, Rotation) Y, Z = True

    I hope it will walk like a character when it moves.

    I do not know if there is a problem with C # or if there is a problem with the Inspector.

    May i have to rewrite it with Navmesh in C#?

    please answer about my question :)
     
    Last edited: May 21, 2019