Unity3d C# 鼠标点击下物体,物体匀速旋转180°,要看到旋转过程,这个代码怎么写?

   更新日期:2024.06.04
  1. 将我下面的脚本挂到场景中

  2. 创建目标物体Cube  这里使用射线检测物体名字实现的

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

    public class RotateCube : MonoBehaviour
    {
        bool startRotate;
        Transform aimCube;
        float speed = 1f;    
        void Update()
        {
            if (Input.GetMouseButtonDown(0))
            {
                Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                RaycastHit hit;
                if (Physics.Raycast(ray, out hit, 100))
                {
                    if (hit.collider.gameObject.name == "Cube")
                    {
                        aimCube = hit.collider.transform;
                        startRotate = true;
                    }
                }
            }

            if (startRotate && aimCube.localEulerAngles.y < 180)
            {
                aimCube.Rotate(Vector3.up * speed);
            }
        }
    }


你可以使用第一人称视角,是Unity自带的,在Assets->Import Package->Character Control,导入这个包就好了,然后选择First Pers。。。那什么的,拖进层次视图中就行了。希望能帮到你。如果你想学习的话,你可以参考那个脚本。其次,你也可以去网上找些资料,像雨松的Unity3D游戏开发,应该比较适合你,里边有相关的代码。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class zhuandong : MonoBehaviour {
    private float jiaoDu;
    private int speed=30;

    private bool isClick;
 void Start () {
        jiaoDu = 0;
        isClick = false;
    }
 
 void Update () {
        jiaoDu += Time.deltaTime * speed;
        if (isClick)
        {
            if (jiaoDu < 180)
            {
                transform.Rotate(Vector3.up * Time.deltaTime * speed);//rotate实在原有基础下继续运行的
            }
            else isClick = false;
        }
      
 }
 //点击物体运行的函数
    private void OnMouseDown()
    {
        jiaoDu = 0;
        isClick = true;
    }
}

将脚本挂在物体上就行了,通俗易懂的代码,有什么不懂的请回复



相关链接

欢迎反馈与建议,请联系电邮
2024 © 视觉网