如何解决为什么在我的 2D 鸟瞰游戏中,我的角度有偏差,但运动可以正常工作?
我正在 JS 中创建一个鸟瞰图,2D 游戏,不使用引擎/库(更多用于学习挑战)。我让角色运动与 WASD 一起工作,其中角色将前进 (W) 或后退 (S),具体取决于他们当前的 direction
(A 向左转,D 向右转),但是当我输出角度时(direction
) 在游戏时间我得到了意想不到的结果。
例如,当玩家面朝“向上”并且我按下“W”时,玩家向上移动,并且获得输出的 direction
为 90°
- 正如预期的那样。当面向“向下”并按“S”时,玩家向下移动,direction
为 270°
- 正如预期的那样。
但是,当面向左时,我按下“W”,字符确实向左移动但是输出direction
是0°
,当面对 + 向右移动时,它是 180°
- 与我预期的完全相反。
这些是移动我的球员的功能:
// Turning
_resetAngle(angle) {
if (angle >= 360) { return 0 }
if (angle < 0) { return 359 }
return angle
}
updateDirection(player,keyboardInput) {
let currentDirection = player.direction
const turnedLeft = keyboardInput['a']
const turnedRight = keyboardInput['d']
if (turnedLeft) { currentDirection -= this.turnAngle }
if (turnedRight) { currentDirection += this.turnAngle }
player.setDirection(this._resetAngle(currentDirection))
}
//Moving
_calculateNewCoords(movingForward,entity) {
let newX
let newY
// please ignore the code duplication,just testing for now
if (movingForward) {
newX = entity.getX() - entity.speed * Math.cos(entity.direction * (Math.PI / 180))
newY = entity.getY() - entity.speed * Math.sin(entity.direction * (Math.PI / 180))
}
else {
newX = entity.getX() + entity.speed * Math.cos(entity.direction * (Math.PI / 180))
newY = entity.getY() + entity.speed * Math.sin(entity.direction * (Math.PI / 180))
}
return { newX,newY }
}
updateCoordinatesByKeyboard(entity,keyboardInput) {
const movingForward = keyboardInput['w']
const movingBackwards = keyboardInput['s']
if ((movingForward && movingBackwards) || !(movingForward || movingBackwards)) { return }
const { newX,newY } = this._calculateNewCoords(movingForward,entity)
if (this._canMove(entity,newX,newY)) { return entity.setXY(newX,newY) }
}
这是渲染玩家的部分:
drawCharacter(character,image) {
const scale = this._getScale(character) // for a 'breathing' effect,makes character grow and shrink
this.context.setTransform(scale,scale,this.windowDimensions.width / 2,this.windowDimensions.height / 2)
this.context.rotate(character.direction * Math.PI / 180)
this.context.drawImage(image,-image.width / 2,-image.height / 2)
}
打印 player.direction
时的结果:
输出:90
(如预期)
输出:180
(期望为 0)
输出:270
(如预期)
输出:0
(预计为 180)
输出:135
(预计为 45)
输出:315
(预计为 225)
再次重申 - 玩家按预期移动(即按下 WASD 使玩家正确转动和移动) - 但输出 direction
出乎意料,我会想解决这个问题,因为将来我想将 NPC 设置为特定角度(即面向 45°),并希望它们面向该方向而无需计算“镜像”方向。
在此先感谢您的帮助!
解决方法
我不会说你得到的值没有意义——恰恰相反——正如我所期望的。因此,这更像是一个“外观”问题,因为您的其他游戏对象也是如此。
尽管如此,您可以通过以下方式轻松地将输出重新计算为您想要的值:
output = Math.abs((input + 90) % 360 - 270)
这将使:
90 -> 90
180 -> 0
270 -> 270
0 -> 180
135 -> 45
315 -> 225
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。