Unity calculates Input input based on the position of the target point

When a target point is given, if the target goes directly to the target point, we can directly make the position point to the position of the target point.

What about transforming input?
Example: For example, there are two parameters X and Y in a character animation, X (- 1 , 1) means walking left and right, Y (-1 , 1) means walking backward and forward.
If I give a target point, how can I calculate what value should be given to the animation?

It's actually very simple, we first calculate the vector of the target point. It will change when your own character is rotated. At this time, you can use the transform.InverseTransformDirection(dir) function to convert the world vector into a local vector.

Let's take a look at the result:
when the green ball is in the front, it calculates that Z = 1
insert image description here
and rotates itself, and the target changes to the front, and it is still Z = 1.

The test code is as follows:

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

public class TestPoints : MonoBehaviour
{
    
    
    public Transform target;

    string showtxt;
    GUIStyle fontStyle = new GUIStyle();

    private void Awake()
    {
    
    
        fontStyle.normal.background = null;    //设置背景填充
        fontStyle.normal.textColor = new Color(1, 0, 0);   //设置字体颜色
        fontStyle.fontSize = 36;       //字体大小
    }
    // Update is called once per frame
    void Update()
    {
    
    
        Vector3 at = target.position;
        at.y = transform.position.y;
        Vector3 dir = (at - transform.position).normalized;
        Debug.DrawRay(transform.position, dir, Color.red, 1f);

        Vector3 moveInput = transform.InverseTransformDirection(dir);
        showtxt = moveInput.ToString("F2");
    }
    void OnGUI()
    {
    
    
        GUI.Label(new Rect(200, 200, 680, 50), showtxt, fontStyle);
    }
}

The GIF below is the change of the Input value for one revolution.
Please add a picture description

Guess you like

Origin blog.csdn.net/thinbug/article/details/131813685