Administrator
发布于 2025-03-25 / 5 阅读
0
0

unity 轮子脚本

将scene加入seting build,实现页面切换

实现通过页面下标切换场景,使用 SceneManagement特性

using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class change_btn : MonoBehaviour
{  

    [Tooltip("true为上,false为下,跳转场景index")]
    public void change_scene(bool is_up)
    {
        int scenenum = SceneManager.sceneCountInBuildSettings;
        int curindex = SceneManager.GetActiveScene().buildIndex;
        UnityEngine.Debug.Log(scenenum);
        if (is_up && curindex+1>=scenenum) return;
        if (!is_up &&curindex<=0) return;
        if (is_up) SceneManager.LoadScene(curindex + 1);
        else SceneManager.LoadScene(curindex - 1);
    }
}

在屏幕上显示一个文字

首先,创建一个Canvas,并将其Render Mode设置为World Space。然后,将Canvas的Event Camera设置为游戏运行时所用的相机。接着,通过调整Canvas的Rect Transform组件的Width, Height, Scale属性,使其大小在世界空间中合适1

在Canvas下创建UI元素,例如Image或Text。可以使用TextMeshPro来创建文字元素,并设置AutoSize,使文字自适应大小。最后,编写一个C#脚本,将Canvas的世界坐标设置为游戏物体的坐标,欧拉角设置为相机的欧拉角1


using UnityEngine;


public class DisplayText : MonoBehaviour

{

public GameObject targetObject; // 目标物体

public Canvas canvas; // Canvas对象


void Update()

{

// 将Canvas的位置设置为目标物体的位置

canvas.transform.position = targetObject.transform.position;

// 将Canvas的旋转设置为相机的旋转

canvas.transform.rotation = Camera.main.transform.rotation;

}

}

使用鼠标悬浮事件

另一种方法是使用鼠标悬浮事件来显示文字信息。可以通过实现IPointerEnterHandler和IPointerExitHandler接口来检测鼠标进入和离开物体的事件2

using UnityEngine;

using UnityEngine.EventSystems;

using UnityEngine.UI;


public class HoverText : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler

{

public Text hoverText; // 显示文字的Text对象


public void OnPointerEnter(PointerEventData eventData)

{

hoverText.gameObject.SetActive(true); // 显示文字

}


public void OnPointerExit(PointerEventData eventData)

{

hoverText.gameObject.SetActive(false); // 隐藏文字

}

}

在3D对象上显示文字

在3D对象上显示文字,可以通过在NGUI中创建一个UILabel或Sprite,然后在3D对象上创建一个空物体,将UI文字显示在该位置。通过控制显示位置到相机的距离,对UI对象进行缩放,实现近大远小的效果3

using UnityEngine;


public class BuildHeadWord : MonoBehaviour

{

public GameObject head; // 头顶的点

public Transform ui; // 头顶的字


private float baseFomat; // 默认字与摄像机的距离

private float currentFomat; // 当前相机的距离

private float scale;


void Start()

{

baseFomat = Vector3.Distance(head.transform.position, Camera.main.transform.position);

scale = 1 - ui.localScale.x; // 默认缩放差值

currentFomat = 0;

}


void Update()

{

if (baseFomat != currentFomat)

{

currentFomat = Vector3.Distance(head.transform.position, Camera.main.transform.position);

float myscale = baseFomat / currentFomat - scale; // 计算出缩放比例

ui.position = WorldToUI(head.transform.position); // 计算UI显示的位置

ui.localScale = Vector3.one * myscale; // 缩放UI

}

}


public static Vector3 WorldToUI(Vector3 point)

{

Vector3 pt = Camera.main.WorldToScreenPoint(point); // 将世界坐标转换为视口坐标

Vector3 ff = UICamera.currentCamera.ScreenToWorldPoint(pt); // 将视口坐标转换为世界坐标

ff.z = 0;

return ff;

}

}

摄像机的自由移动

//==========================
// - FileName: CameraControl.cs
// - Created: yeyuotc
// - CreateTime: #CreateTime#
// - Email: 1079221637@qq.com
// - Description:
//==========================
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraControl: MonoBehaviour
{
    public Transform tourCamera;
    #region 相机移动参数
    public float moveSpeed = 1.0f;
    public float rotateSpeed = 90.0f;
    public float shiftRate = 2.0f;// 按住Shift加速
    public float minDistance = 0.5f;// 相机离不可穿过的表面的最小距离(小于等于0时可穿透任何表面)
    #endregion

    #region 运动速度和其每个方向的速度分量
    private Vector3 direction = Vector3.zero;
    private Vector3 speedForward;
    private Vector3 speedBack;
    private Vector3 speedLeft;
    private Vector3 speedRight;
    private Vector3 speedUp;
    private Vector3 speedDown;
    #endregion
    void Start()
    {
        if (tourCamera == null) tourCamera = gameObject.transform;
        // 防止相机边缘穿透
        //if (tourCamera.GetComponent<Camera>().nearClipPlane > minDistance / 3)
        //{
        //    tourCamera.GetComponent<Camera>().nearClipPlane /= 3;
        //}
    }
    void Update()
    {
        GetDirection();
        // 检测是否离不可穿透表面过近
        RaycastHit hit;
        while (Physics.Raycast(tourCamera.position, direction, out hit, minDistance))
        {
            // 消去垂直于不可穿透表面的运动速度分量
            float angel = Vector3.Angle(direction, hit.normal);
            float magnitude = Vector3.Magnitude(direction) * Mathf.Cos(Mathf.Deg2Rad * (180 - angel));
            direction += hit.normal * magnitude;
        }
        tourCamera.Translate(direction * moveSpeed * Time.deltaTime, Space.World);
    }
    private void GetDirection()
    {
        #region 加速移动
        if (Input.GetKeyDown(KeyCode.LeftShift)) moveSpeed *= shiftRate;
        if (Input.GetKeyUp(KeyCode.LeftShift)) moveSpeed /= shiftRate;
        #endregion

        #region 键盘移动
        // 复位
        speedForward = Vector3.zero;
        speedBack = Vector3.zero;
        speedLeft = Vector3.zero;
        speedRight = Vector3.zero;
        speedUp = Vector3.zero;
        speedDown = Vector3.zero;
        // 获取按键输入
        if (Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.W)) speedForward = tourCamera.forward;
        if (Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.S)) speedBack = -tourCamera.forward;
        if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A)) speedLeft = -tourCamera.right;
        if (Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.D)) speedRight = tourCamera.right;
        if (Input.GetKey(KeyCode.E)) speedUp = Vector3.up;
        if (Input.GetKey(KeyCode.Q)) speedDown = Vector3.down;
        direction = speedForward + speedBack + speedLeft + speedRight + speedUp + speedDown;
        #endregion

        #region 鼠标旋转
        if (Input.GetMouseButton(1))
        {
            // 转相机朝向
            tourCamera.RotateAround(tourCamera.position, Vector3.up, Input.GetAxis("Mouse X") * rotateSpeed * Time.deltaTime);
            tourCamera.RotateAround(tourCamera.position, tourCamera.right, -Input.GetAxis("Mouse Y") * rotateSpeed * Time.deltaTime);
            // 转运动速度方向
            direction = V3RotateAround(direction, Vector3.up, Input.GetAxis("Mouse X") * rotateSpeed * Time.deltaTime);
            direction = V3RotateAround(direction, tourCamera.right, -Input.GetAxis("Mouse Y") * rotateSpeed * Time.deltaTime);
        }
        #endregion

        #region 鼠标滚轮效果
        if (Input.GetAxis("Mouse ScrollWheel") < 0)
        {
            if (Camera.main.fieldOfView <= 100)
                Camera.main.fieldOfView += 2;
            if (Camera.main.orthographicSize <= 20)
                Camera.main.orthographicSize += 0.5F;
        }
        //Zoom in
        if (Input.GetAxis("Mouse ScrollWheel") > 0)
        {
            if (Camera.main.fieldOfView > 2)
                Camera.main.fieldOfView -= 2;
            if (Camera.main.orthographicSize >= 1)
                Camera.main.orthographicSize -= 0.5F;
        }
        #endregion
    }

    public Vector3 V3RotateAround(Vector3 source, Vector3 axis, float angle)
    {
        Quaternion q = Quaternion.AngleAxis(angle, axis);// 旋转系数
        return q * source;// 返回目标点
    }
}



评论