以下是在Unity中使用C#脚本实现鼠标右键点击后,在相机左上角位置生成一个预制体,并向鼠标右键位置移动,到达位置后销毁,使用协程来完成的示例代码:

using System.Collections;
using UnityEngine;

public class MouseClick : MonoBehaviour
{
    public GameObject prefab; // 预制体

    void Update()
    {
        if (Input.GetMouseButtonDown(1)) // 检测鼠标右键点击事件
        {
            StartCoroutine(MovePrefab());
        }
    }

    IEnumerator MovePrefab()
    {
        Vector3 startPos = Camera.main.ViewportToWorldPoint(new Vector3(0, 1, Camera.main.nearClipPlane)); // 获取相机左上角位置
        GameObject newPrefab = Instantiate(prefab, startPos, Quaternion.identity); // 在相机左上角位置生成预制体

        Vector3 targetPos = Camera.main.ScreenToWorldPoint(Input.mousePosition); // 获取鼠标点击位置
        float distance = Vector3.Distance(startPos, targetPos); // 计算起始位置和目标位置之间的距离

        float speed = 5f; // 移动速度
        float t = 0f; // 当前移动时间

        while (t < distance / speed) // 在规定时间内移动到目标位置
        {
            t += Time.deltaTime;
            newPrefab.transform.position = Vector3.Lerp(startPos, targetPos, t * speed / distance);
            yield return null;
        }

        Destroy(newPrefab); // 销毁预制体
    }
}

代码解释:

  1. 在Update()函数中,通过Input.GetMouseButtonDown(1)检测鼠标右键点击事件。
  2. 在MovePrefab()协程中,首先获取相机左上角的位置作为起始位置,然后在该位置生成预制体。
  3. 然后获取鼠标点击位置,并计算起始位置和目标位置之间的距离。
  4. 在循环中,通过插值运算实现预制体从起始位置移动到目标位置。
  5. 循环结束后,销毁预制体
unity脚本鼠标右键后在相机左上角位置生成一个预制体然后向鼠标右键位置移动到达位置后销毁使用协程来完成添加注释

原文地址: https://www.cveoy.top/t/topic/h7at 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录