在 Unity 中,我有一個相機作為 2D 游戲物件的子項(跟隨它)。有一個 IF 陳述句可以讓我通過按住一個鍵向前移動相機。我需要一個代碼在我放手后將相機回傳給游戲物件。感謝您的幫助。
public class camera : MonoBehaviour
{
public float panspeed = 30f;
public float panBorderThickness = 30f;
public GameObject ship1;
private Vector3 offset;
void Update()
{
if (Input.GetKey("f"))
{
Vector3 pos = transform.position;
if (Input.mousePosition.y >= Screen.height - panBorderThickness)
{
pos.y = panspeed * Time.deltaTime;
}
if (Input.mousePosition.y <= panBorderThickness)
{
pos.y -= panspeed * Time.deltaTime;
}
if (Input.mousePosition.x >= Screen.width - panBorderThickness)
{
pos.x = panspeed * Time.deltaTime;
}
if (Input.mousePosition.x <= panBorderThickness)
{
pos.x -= panspeed * Time.deltaTime;
}
transform.position = pos;
}
//something to return the camera back when i let go of F key
}
}
uj5u.com熱心網友回復:
如果我理解正確,您會希望將相機平穩地移回其原始位置,因此我可能會這樣做
private void Update ()
{
if (Input.GetKey(KeyCode.F))
{
var pos = transform.position;
if (Input.mousePosition.y >= Screen.height - panBorderThickness)
{
pos.y = panspeed * Time.deltaTime;
}
if (Input.mousePosition.y <= panBorderThickness)
{
pos.y -= panspeed * Time.deltaTime;
}
if (Input.mousePosition.x >= Screen.width - panBorderThickness)
{
pos.x = panspeed * Time.deltaTime;
}
if (Input.mousePosition.x <= panBorderThickness)
{
pos.x -= panspeed * Time.deltaTime;
}
transform.position = pos;
}
else
{
transform.position = Vector3.MoveTowards(transform.position, ship1.transform.position - ship1.transform.forward * 10, panspeed * Time.deltaTime);
}
}
uj5u.com熱心網友回復:
if(Input.GetKeyUp("f")){
transform.position = ship1.transform.position;
}
旁注,您不能只為向量的一個分量賦值。您需要使用新組件重新分配整個向量或添加/減去原始向量。你的腳本應該看起來像
if (Input.GetKey("f"))
{
Vector3 pos = transform.position;
if (Input.mousePosition.y >= Screen.height - panBorderThickness)
{
pos = new Vector3(0, panspeed * Time.deltaTime, 0);
}
if (Input.mousePosition.y <= panBorderThickness)
{
pos -= new Vector3(0, panspeed * Time.deltaTime, 0);
}
if (Input.mousePosition.x >= Screen.width - panBorderThickness)
{
pos = new Vector3(panspeed * Time.deltaTime, 0, 0);
}
if (Input.mousePosition.x <= panBorderThickness)
{
pos -= new Vector3(panspeed * Time.deltaTime, 0, 0);
}
transform.position = pos;
}
if(Input.GetKeyUp("f"))
{
transform.position = GameObjectYouWant.transform.position;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/388819.html
