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

时间:2014-08-08 18:27:48

标签: unity3d unityscript

现在我的物体只能向右和向左移动。 我想要的是,如果我向右移动它将停在背景图像的侧边边缘上,左侧也是如此。

背景:

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);
}

1 个答案:

答案 0 :(得分: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));