我有一个上下移动的目标,但我不确定如何将它的垂直移动限制在某个y轴范围内。谢谢你的建议。代码如下:
using UnityEngine;
using System.Collections;
public class TargetMovementVertical : MonoBehaviour
{
public int maxSpeed;
private Vector3 startPosition;
// Use this for initialization
void Start ()
{
maxSpeed = 3;
startPosition = transform.position;
}
// Update is called once per frame
void Update ()
{
MoveVertical ();
}
void MoveVertical()
{
transform.position = new Vector3(transform.position.x, startPosition.y + Mathf.Sin(Time.time * maxSpeed), transform.position.z);
if(transform.position.y > 1.0f)
{
transform.position = new Vector3(transform.position.x, transform.position.y, transform.position.z);
}
else if(transform.position.y < -1.0f)
{
transform.position = new Vector3(transform.position.x, transform.position.y, transform.position.z);
}
}
}
答案 0 :(得分:3)
您的问题可能有两个含义:
1-如果要将y shift限制在-1到1之内,请使用以下代码: (例如,如果您的原始y等于5,则结果将在范围(4,6)
内transform.position = new Vector3(0, startPosition.y + Mathf.Sin(Time.time * maxSpeed), 0);
2-如果要使y值始终在-1到1之间,请使用以下代码: (无论原始y值如何,您的结果y值都将在范围(-1,1)内)
transform.position = new Vector3(transform.position.x, Mathf.Sin(Time.time * maxSpeed), transform.position.z);
答案 1 :(得分:2)
private Vector3 startPosition;
bool up=true;
// Use this for initialization
void Start ()
{
//maxSpeed = 3;
startPosition = transform.position;
}
// Update is called once per frame
void Update ()
{
MoveVertical ();
}
void MoveVertical()
{
var temp=transform.position;
print (up);
if(up==true)
{
temp.y += 0.01f;
transform.position=temp;
if(transform.position.y>=0.39f)
{
up = false;
}
}
if(up==false)
{
temp.y -= 0.01f;
transform.position=temp;
if(transform.position.y<=0.14f)
{
up = true;
}
}
}
根据需要调整您的值。