Unity Scripts 学习笔记 - 005.官方代码案例之 Quaternion.LookRotation( ) ;

需求:实现主物体 Z 轴朝向目标体,并实时跟随旋转;

代码实现:

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

public class ScriptOfQuaternion : MonoBehaviour
{
    
    
    public Transform target;
    public float distance = 10f;

    void Update()
    {
    
    
        Vector3 targetPos = target.position - this.transform.position;
        Quaternion targetRot = Quaternion.LookRotation(targetPos, new Vector3(0, 1, 0));
        target.rotation = targetRot;
    }

    private void FixedUpdate()
    {
    
    
        Debug.DrawLine(Vector3.zero, target.forward, Color.blue, distance);
        Debug.DrawLine(Vector3.zero, target.right, Color.red, distance);
        Debug.DrawLine(Vector3.zero, target.up, Color.green, distance);
    }
}

官方示例地址直达链接:

https://docs.unity3d.com/cn/2021.1/ScriptReference/Quaternion.LookRotation.html

猜你喜欢

转载自blog.csdn.net/m0_54122551/article/details/124654635