【问题标题】:Bounce off screen Unity 2D屏幕反弹 Unity 2D
【发布时间】:2019-08-01 05:11:15
【问题描述】:

我正在尝试制作一个 2D 游戏,其中一个球在 Unity 中从相机边缘反弹。现在,如果我理解正确的话,Unity 更多的是,你制作和环境,然后对齐相机,而不是制作环境以适应相机,对吧?

我可以得到球的位置,然后看它是否大于某个值,然后施加一个力,这就是我正在做的,但是使用不同的设备,屏幕比例会发生变化,所以这不起作用.有没有办法检测它是否只是碰到相机/视图的边缘或我可以使用的某个百分比单位?在这个游戏中,摄像头随着球上下移动,所以只有左右两侧需要“有弹性”。

当我查看此内容时,有人建议使用设置在相机边缘的屏障。随着所有缩放和比例方面的变化,我认为检测边缘会更容易,无论是使用某种方法来获取以像素为单位的屏幕宽度,还是其他方式。

【问题讨论】:

  • 您可以使用Screen.widthScreen.height获取分辨率
  • @Savaria 这在任何脚本文件中(认为技术术语是类),就像您不必进入相机一样,它以像素为单位?
  • 您可以使用IsVisibleFrom查看您的对象是否在相机中frustum
  • @AliKanat,有趣,你知道它是在碰到边缘时触发还是完全熄灭?
  • 文档在 Unity Scripting API (link) 是的,它以像素为单位,不,它是关于游戏的窗口,而不是特定的相机

标签: unity3d 2d-games


【解决方案1】:

一种方法是将球的位置转换为屏幕位置,然后验证它是否离开屏幕(如果位置有 xy 小于 0x 大于 屏幕宽度y 大于 屏幕高度 )。

Vector2 screenPosition = Camera.main.WorldToScreenPoint(this.transform.position);
if((screenPosition.y > Screen.height) || (screenPosition.y < 0f) || (screenPosition.x > Screen.width) || (screenPosition.x <0f))
{   
    screenPosition.x = Mathf.Clamp(screenPosition.x, 0f, Screen.width);
    screenPosition.y = Mathf.Clamp(screenPosition.y, 0f, Screen.height);
    Vector3 newWorldPosition = Camera.main.ScreenToWorldPoint(screenPosition);
    this.transform.position = new Vector2(newWorldPosition.x, newWorldPosition.y);
    Move();
}
private void Move()
{
    velocity *= -1f;
    rigidBody.velocity = velocity;
}

在此示例中,脚本将检查球是否离开屏幕,如果是,则在屏幕边缘之间固定位置并更改速度,以便球向相反方向反弹。请注意下面的GIF,如果我更改纵横比,球在接触边缘时仍会弹跳。

【讨论】:

    【解决方案2】:
    var dist = (this.transform.position 
    - Camera.main.transform.position).z;
    
    var leftBorder = 
    Camera.main.ViewportToWorldPoint(new 
    Vector3(0,0,dist)).x;
    var rightBorder = 
    Camera.main.ViewportToWorldPoint(new 
    Vector3(1,0,dist)).x;
    var topBorder = 
    Camera.main.ViewportToWorldPoint(new 
    Vector3(0,0,dist)).y;
    var bottomBorder = 
    Camera.main.ViewportToWorldPoint(new 
    Vector3(0,1,dist)).y;
    
    Vector3 playerSize = 
    
    
    this.gameObject. 
    renderer.bounds.size;
    
    this.transform.position = new 
    Vector3 (
    
    Mathf.Clamp(this. 
    transform.position.x, 
    leftBorder + playerSize.x/2, 
    rightBorder - playerSize.x/2),
    Mathf.Clamp 
    (this.transform.position.y, 
    topBorder + playerSize.y/2, 
    bottomBorder - playerSize.y/2),
    this.transform.position.z
    

    这就是我使用的。这是统一答案的答案。

    【讨论】:

    • 你检查过这个吗。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多