首页 > 解决方案 > How to stop my character going off-screen?

问题描述

I want my character to stop everytime I hit the edge of the screen/canvas, so I added some rectangle at the end of each border(with a 2d collider), so my character will collide with it and stop moving in that direction, but the thing is that if, for example, I hit the left rectangle and I still press A to move left, my character strarts 'shaking'. I tried to solve that by setting the speed of it to 0 when it hits the certain rectangle, but then I cant move at all in any directions after I get to the edge.

public class CharacterMovement : MonoBehaviour {

public float speed = 5f;



void Start() {


}


void Update() {
    if (Input.GetKey(KeyCode.W))
    {
        transform.Translate(0, speed * Time.deltaTime, 0);
    }
    if (Input.GetKey(KeyCode.S))
    {
        transform.Translate(0, -speed * Time.deltaTime, 0);
    }
    if (Input.GetKey(KeyCode.A))
    {
        transform.Translate(-speed * Time.deltaTime, 0, 0);
    }
    if (Input.GetKey(KeyCode.D))
    {
        transform.Translate(speed * Time.deltaTime, 0, 0);
    }
}


void OnCollisionEnter2D(Collision2D col)
{
    if (col.gameObject.name == "offscreen")
    {
        speed = 0f;
    }else
    {
        speed = 5f;
    }
}

}

标签: c#unity3dcollisionoff-screen

解决方案


我不熟悉单声道行为方法,但我认为问题在于当你等于边缘时,它在下一次更新中保持不变。由于没有任何东西使它成为错误,因此速度保持为 0。

尝试在您的更新方法中检查每个按下的键。

就像是

if (key ==moveleft)
{
    if(sprite.leftedge>edgeoftheleftscreen+1)
         Sprite.moveleft();   
}
if(key==moveright)
{
    if(sprite.rightedge<edgeoftherightscreen-1)
         Sprite.moveright();
}

希望这可以帮助。


推荐阅读