using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Rotateturret : MonoBehaviour
{
public enum RotateOnAxis { rotateOnX, rotateOnY, rotateOnZ };
public bool randomRotation = false;
[Range(0, 360)]
public int rotationRange = 70;
private void Start()
{
}
private void Update()
{
if (randomRotation == true)
{
var rr = Random.Range(-rotationRange, rotationRange);
transform.Rotate(Vector3.up, rr);
}
}
}
它现在做什么它继续添加或删除旋转的随机数,所以在某些情况下旋转可以是230或450或21它在-70到70的范围内添加/删除但是我希望它添加/删除但是从原始起始位置/旋转只有70 / -70。
例如,如果游戏开始且对象旋转为20,那么添加/删除70,旋转将在20 + 70和20-70之间随机变化,最大可达90,最小为-50。
答案 0 :(得分:1)
Rotate
将相对于当前轮换行动,因此您实际上在那里累积轮换。试试这个;
Quaternion initialRotation;
void Start ()
{
// Save initial rotation
initialRotation = transform.rotation;
}
void Update ()
{
// Compute random angle in the range of +- rotationRange
var delta = (Random.value * 2f - 1f) * rotationRange;
// Compute rotation from the initial rotation and delta
transform.rotation = initialRotation * Quaternion.Euler(0f, delta, 0f);
}
答案 1 :(得分:1)
我相信使用“currentRotation”变量和“startRotation”变量并向其添加随机值将起作用。我在下面的部分中将它添加到您现有的脚本中。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Rotateturret : MonoBehaviour
{
public enum RotateOnAxis { rotateOnX, rotateOnY, rotateOnZ };
public bool randomRotation = false;
[Range(0, 360)]
public int rotationRange = 70;
public int startRotation = 20; //create a startRotation value.
public int currentRotation = 20; //create a currentRotation value in case you need to access it later.
private void Update()
{
if (randomRotation == true)
{
var rr = Random.Range(-rotationRange, rotationRange);
currentRotation = startRotation + rr; //Add the random value to the start value. This also works for negative values.
transform.Rotate(Vector3.up, currentRotation); //use the combined value instead of just rr.
}
}
}