In Unity's Update, judge the direction of movement by the position of the object itself

In the Update method of Unity, the direction of movement is judged by the position of the object itself

1. Create a Cube object in the Unity scene.

insert image description here

2. Create a new script named "JudgeDirection".

Open the script, write the following code, and save it:

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

public class JudgeDirection : MonoBehaviour
{
    
    
    private float originValue;

    void Start()
    {
    
    
        originValue = transform.position.x;
    }

    void Update()
    {
    
    
        if (originValue - transform.position.x > 0)
        {
    
    
            Debug.Log("物体往左移动");
        }
        else if (originValue - transform.position.x < 0)
        {
    
    
            Debug.Log("物体往右移动");
        }
        originValue = transform.position.x;
    }
}

The script can only judge whether the object is moving to the left or to the right. If you want to judge the movement of an object back and forth, you only need to modify the axis of the object itself, that is, change transform.position.x to transform.position.z or transform.position.y.

3. Running scenario

Drag and drop the X axis of the Cube object to output relevant information on the Console console.
insert image description here

Guess you like

Origin blog.csdn.net/jianjianshini/article/details/120140346