问题描述
我正在编写一个Phaser 3教程(用于制作2d和3d游戏的javascript框架),并且我想知道Phaser 3如何通过以下简单计算处理y位置:
/**
* @param {Phaser.GameObjects.Sprite} Sprite
*/
addCarrotAbove(sprite)
{
// this one!!!!!
const y = sprite.y - sprite.displayHeight
/** @type {Phaser.Physics.Arcade.Sprite} */
const carrot = this.carrots.get(sprite.x,y,'carrot')
this.add.existing(carrot)
carrot.body.setSize(carrot.width,carrot.height)
return carrot
}
,当解析此函数的另一个对象时,它代替了sprite是我编写的/迭代的自动平台回收对象:
```update(t,dt)
{
this.platforms.children.iterate(child => {
/** @type {Phaser.Physics.Arcade.Sprite} */
const platform = child
const scrollY = this.cameras.main.scrollY
if (platform.y >= scrollY + 600)
{
platform.y = scrollY - 60
platform.body.updateFromGameObject()
// create a carrot above the platform being reused
this.addCarrotAbove(platform)
}
})```
它会自动将胡萝卜放在平台顶部(执行功能时)
它是如何做到的?我唯一感兴趣的行是我用const创建的y变量。胡萝卜的位置是通过这种简单的计算得出的,但我不明白每次胡萝卜是如何将胡萝卜放在平台上的。谢谢stackoverflow社区!
解决方法
没关系,我知道了。对于有相同问题但不可能存在相同问题的任何人,我编写的回收平台功能使用摄像机滚动条将平台向上发送,从而使Y坐标为负值。为了生成不在平台内部(即sprite.y)和平台上方的胡萝卜,请减去sprite的显示高度,不要将两者相加,因为sprite.y为负值,将其减去即可将胡萝卜向上发送一定数量的显示高度像素。希望我能帮上忙。