尝试从屏幕边缘反弹时物体卡住了,我做错了吗? [英] Object gets stuck when trying to bounce off screen edges, am I doing this wrong?

查看:104
本文介绍了尝试从屏幕边缘反弹时物体卡住了,我做错了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class AsteroidMovement : MonoBehaviour
{

public Vector2 speed;
public Vector2 direction;
private Vector2 movement;

private Vector3 TopScreenBound;
private Vector3 BottomScreenBound;

// Use this for initialization
void Start()
{
    TopScreenBound = Camera.main.ViewportToWorldPoint(new Vector3(0f, 1f, 0f));
    BottomScreenBound = Camera.main.ViewportToWorldPoint(new Vector3(0f, 0f, 0f));
}

// Update is called once per frame
void Update()
{
    if (gameObject.transform.position.y >= TopScreenBound.y)
    {
        direction.y *= -1;
    }

    if (gameObject.transform.position.y <= BottomScreenBound.y)
    {
        direction.y *= -1;
    }

    movement = new Vector2(speed.x * direction.x, speed.y * direction.y);
}

void FixedUpdate()
{

    rigidbody2D.velocity = movement;
}
}

我正在尝试让游戏中的小行星从屏幕边缘弹起,并且使它运行正常,但是经过几次弹跳,小行星/物体会卡在"墙壁上并在游戏区域内出现故障

I am trying to have asteroids in my game bounce off the edge of my screen and I have got it working decently, but after a few bounces, the asteroid/object gets "stuck" in the wall and glitches out the playing area.

我要解决这个问题吗?我看不出代码在几次弹跳后会卡住小行星的地方.在此先感谢:)

Am I going about this wrong? I cannot see where in the code its making the asteroids stuck after a couple of bounces.Thanks in advance :)

推荐答案

如果您的对象已经在屏幕之外并且不能完全移动,则必须固定对象的位置才能在屏幕内 弹跳.在下一帧输入屏幕空间,然后您的对象将无限地改变其方向,直到它进入或离开屏幕为止.

You must fix your object's position to bounce inside the screen, if your object is already outside of the screen and it does not fully enter in screen space in the next frame, then your object is changing it's direction infinitely until it enters or leaves the screen.

更改此:

if (gameObject.transform.position.y >= TopScreenBound.y)
{
    direction.y *= -1;
}

if (gameObject.transform.position.y <= BottomScreenBound.y)
{
    direction.y *= -1;
}

对此:

if (gameObject.transform.position.y >= TopScreenBound.y)
{
    gameObject.transform.position.y = TopScreenBound.y;
    direction.y *= -1;
}

if (gameObject.transform.position.y <= BottomScreenBound.y)
{
    gameObject.transform.position.y = BottomScreenBound.y;
    direction.y *= -1;
}

这篇关于尝试从屏幕边缘反弹时物体卡住了,我做错了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆