首页 > 解决方案 > 在游戏中排除某个方向的问题

问题描述

我正在努力实现我的玩家如何只能在一个方向上行走......例如:当玩家在 x 方向上行走时,他不能只在 y 方向上在 -x 方向上行走,对于 y 也是如此。例如,如果他在 -y 中行走,他就无法更改为 y。

谢谢你的帮助!下面是我如何切换播放器的方向:

 this.changeDirection = function(direction) {
    switch(direction) {
        case "Up":
            this.xSpeed = 0;
            this.ySpeed = -scale;
            break; 
        case "Down":
            this.xSpeed = 0;
            this.ySpeed = scale;
            break; 
        case "Left":
            this.xSpeed = -scale;
            this.ySpeed = 0;
            break; 
        case "Right":
            this.xSpeed = scale;
            this.ySpeed = 0;
            break;
    }
}

标签: javascript

解决方案


对于Upand ,在每个赋值块之前Down添加:if (this.ySpeed === 0)

case "Up":
    if (this.ySpeed === 0) {
        this.xSpeed = 0;
        this.ySpeed = -scale;
    }
    break; 

Left并为&做类似的事情Right


推荐阅读