我确实在Unity中为Cardboard创建了一个小游戏,并且实现了一个与CardboardTrigger和/或阈值一起使用的Autowalk功能。它工作得很好,但我需要添加一个“自动停止”功能。因此,如果我走进立方体,我想创建一个触发器的立方体来阻止玩家走路。
我尝试过类似的事情:
OnTriggerEnter (col : Collider) {
if(col.gameObject.tag == "stop")
}
{
isWalking = false;
}
但是你可以看到我是菜鸟,它不起作用:-) 有人能帮助我吗?会非常非常好!
自动步行功能的代码如下,感谢Jupp Otto:
using UnityEngine;
using System.Collections;
public class Autowalk : MonoBehaviour
{
private const int RIGHT_ANGLE = 90;
// This variable determinates if the player will move or not
private bool isWalking = false;
CardboardHead head = null;
//This is the variable for the player speed
[Tooltip("With this speed the player will move.")]
public float speed;
[Tooltip("Activate this checkbox if the player shall move when the Cardboard trigger is pulled.")]
public bool walkWhenTriggered;
[Tooltip("Activate this checkbox if the player shall move when he looks below the threshold.")]
public bool walkWhenLookDown;
[Tooltip("This has to be an angle from 0° to 90°")]
public double thresholdAngle;
[Tooltip("Activate this Checkbox if you want to freeze the y-coordiante for the player. " +
"For example in the case of you have no collider attached to your CardboardMain-GameObject" +
"and you want to stay in a fixed level.")]
public bool freezeYPosition;
[Tooltip("This is the fixed y-coordinate.")]
public float yOffset;
void Start ()
{
head = Camera.main.GetComponent<StereoController>().Head;
}
void Update ()
{
// Walk when the Cardboard Trigger is used
if (walkWhenTriggered && !walkWhenLookDown && !isWalking && Cardboard.SDK.Triggered)
{
isWalking = true;
}
else if (walkWhenTriggered && !walkWhenLookDown && isWalking && Cardboard.SDK.Triggered)
{
isWalking = false;
}
// Walk when player looks below the threshold angle
if (walkWhenLookDown && !walkWhenTriggered && !isWalking &&
head.transform.eulerAngles.x >= thresholdAngle &&
head.transform.eulerAngles.x <= RIGHT_ANGLE)
{
isWalking = true;
}
else if (walkWhenLookDown && !walkWhenTriggered && isWalking &&
(head.transform.eulerAngles.x <= thresholdAngle ||
head.transform.eulerAngles.x >= RIGHT_ANGLE))
{
isWalking = false;
}
// Walk when the Cardboard trigger is used and the player looks down below the threshold angle
if (walkWhenLookDown && walkWhenTriggered && !isWalking &&
head.transform.eulerAngles.x >= thresholdAngle &&
Cardboard.SDK.Triggered &&
head.transform.eulerAngles.x <= RIGHT_ANGLE)
{
isWalking = true;
}
else if (walkWhenLookDown && walkWhenTriggered && isWalking &&
head.transform.eulerAngles.x >= thresholdAngle &&
(Cardboard.SDK.Triggered ||
head.transform.eulerAngles.x >= RIGHT_ANGLE))
{
isWalking = false;
}
if (isWalking)
{
Vector3 direction = new Vector3(head.transform.forward.x, 0, head.transform.forward.z).normalized * speed * Time.deltaTime;
Quaternion rotation = Quaternion.Euler(new Vector3(0, -transform.rotation.eulerAngles.y, 0));
transform.Translate(rotation * direction);
}
if(freezeYPosition)
{
transform.position = new Vector3(transform.position.x, yOffset, transform.position.z);
}
}
}
非常感谢周末愉快, 乙