软件编程
位置:首页>> 软件编程>> C#编程>> Unity3D实现旋钮控制灯光效果

Unity3D实现旋钮控制灯光效果

作者:蓝染s  发布时间:2021-09-05 21:16:58 

标签:Unity3D,旋钮,灯光

本文实例为大家分享了Unity3D实现旋钮控制灯光效果的具体代码,供大家参考,具体内容如下

前言

实际上使用的是非常简单的方式,通过开启以及关闭带有灯光效果物体的渲染以模拟出的灯光切换效果。

正确方式应当为物体切换不同的Material实现效果。

所用函数


public void RotateAround(Vector3 point, Vector3 axis, float angle);
//通过给定一个世界坐标、轴向以及一个角度,使物体以该角度旋转绕世界坐标点的轴向的变换

public T GetComponent<T>();
//获取对象的组件

public bool enabled { get; set; }
//设置激活状态

实现代码


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

public class RotateControl : MonoBehaviour {

public GameObject RedLight;//红灯
public GameObject GreenLight;//绿灯
public GameObject Center;//旋转中心,若为自身则指定自身

private bool isOn = false;//正在开启
private bool isOff = false;//正在关闭
[Range(0,180)]
public float onLine = 80;//旋钮最大角度
[Range(0,180)]
private float offLine = 0;//旋钮最小角度
[Range(0,3)]
public float speed = 1;//旋转速度
[Range(0, 20)]
public float LightingRange = 10;//亮灯角度与旋钮最大角度的角度差

// Use this for initialization
void Start () {
isOn = false;
isOff = false;
offLine = Center.transform.rotation.z;//设定起始位置即为最小角度
RedLight.GetComponent<Renderer>().enabled = false;//关闭红灯渲染
GreenLight.GetComponent<Renderer>().enabled = false;//关闭绿灯渲染
}

// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.R))//关闭
{
 isOn = false;
 isOff = true;
}
if (Input.GetKeyDown(KeyCode.G))//开启
{
 isOn = true;
 isOff = false;
}

if (isOn == true)
{
 if (this.transform.eulerAngles.z < onLine)//旋钮旋转至最大角度
 {
 this.transform.RotateAround(this.transform.position, this.transform.forward, speed);
 }
 else
 {
 isOn = false;
 }
}
if (isOff == true)
{
 if (this.transform.eulerAngles.z > offLine + 1)//旋转至最小角度+1°的角度,当物体旋转到0时继续旋转则变为360度
 {
 this.transform.RotateAround(this.transform.position, this.transform.forward, -speed);
 }
 else
 {
 isOff = false;
 }
}

//检测旋转角度控制灯光
if (this.transform.eulerAngles.z >= onLine - LightingRange)//当旋钮旋转角度大于阈值则渲染绿灯,关闭红灯
{
 RedLight.GetComponent<Renderer>().enabled = false;
 GreenLight.GetComponent<Renderer>().enabled = true;
}
else
{
 RedLight.GetComponent<Renderer>().enabled = true;
 GreenLight.GetComponent<Renderer>().enabled = false;
}
}
}

关于物体的旋转

由于很少情况会在物体刚好旋转到我们所期望的角度时进行一次判定,所以物体旋转角度一般会超过你所期望的角度。

当物体由一个正向的角度向0°方向旋转时,物体角度低于0°时物体角度会变为360°

来源:https://blog.csdn.net/qq_36658648/article/details/81135937

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com