如何保持对象仅在背景边框内移动?

问题描述 投票:0回答:1

目前我的物体只能左右移动。 我希望如果我将它移动到右侧,它将停在背景图像最紧的侧边框上,左侧也是如此。

背景:

X : 5.5  
Y : 3 
Z : 1

我正在移动的物体:

X : 1 
Y : 1 
Z : 1

这是我现在使用的脚本:

using UnityEngine;
using System.Collections;

public class Player : MonoBehaviour
{

    public float movementSpeed = 10;

    void Update ()
    {
        if (Input.GetKey (KeyCode.RightArrow)) {
            transform.Translate(Vector2.right * movementSpeed * Time.deltaTime);
        }

        if (Input.GetKey (KeyCode.LeftArrow)) {
            transform.Translate(Vector3.left * movementSpeed * Time.deltaTime);
        }

        if (transform.position.x <= -4.3f) {
            transform.position = new Vector2(-4.3f, transform.position.y);
        } else if (transform.position.x >= 4.3f) {
            transform.position = new Vector2(4.3f, transform.position.y);
        }

        if (transform.position.y <= -2.7f) {
            transform.position = new Vector2(transform.position.x, -2.7f);
        } else if (transform.position.y >= 2.7f) {
            transform.position = new Vector2(transform.position.x, 2.7f);
        }
    }


}

问题在于这部分它没有停在背景的左右边缘:

if (transform.position.x <= -4.3f) {
    transform.position = new Vector2(-4.3f, transform.position.y);
} else if (transform.position.x >= 4.3f) {
    transform.position = new Vector2(4.3f, transform.position.y);
}

if (transform.position.y <= -2.7f) {
    transform.position = new Vector2(transform.position.x, -2.7f);
} else if (transform.position.y >= 2.7f) {
    transform.position = new Vector2(transform.position.x, 2.7f);
}
c# unity-game-engine
1个回答
0
投票

首先,你是怎么得到4.3这个数字的?
如果背景比例为5.5,则左右扩展为2.75。
然后考虑到您的对象大小 (1,1,1),然后您还必须用对象大小的一半减去它。

// 2.25 = 5.5 / 2 (half of background scale) - 0.5 (half of object scale)
if (transform.position.x <= -2.25f) {  
    transform.position = new Vector2(-4.3f, transform.position.y);
} else if (transform.position.x >= 2.25f) {
    transform.position = new Vector2(4.3f, transform.position.y);
}

if (transform.position.y <= -1f) {
    transform.position = new Vector2(transform.position.x, -2.7f);
} else if (transform.position.y >= 1f) {
    transform.position = new Vector2(transform.position.x, 2.7f);
}

然而,限制对象移动的常见方法通常是使用 Mathf.clamp 来完成。上面的代码可以缩短为只有 1 行:

if (transform.position.x <= -2.25f) {  
    transform.position = new Vector2(-4.3f, transform.position.y);
} else if (transform.position.x >= 2.25f) {
    transform.position = new Vector2(4.3f, transform.position.y);
}

if (transform.position.y <= -1f) {
    transform.position = new Vector2(transform.position.x, -2.7f);
} else if (transform.position.y >= 1f) {
    transform.position = new Vector2(transform.position.x, 2.7f);
}

变成:

transform.position = new Vector2(Mathf.Clamp (transform.position.x, -2.25f, 2.25f), 
                                 Mathf.Clamp (transform.position.y, -1f, 1f));
© www.soinside.com 2019 - 2024. All rights reserved.