HTML5画布游戏TypeScript中的事件
我正在开发一款HTML5画布空间入侵者游戏,希望从我的玩家类射击方法(在我的gameObject模块文件中)接收game.ts类中的事件game.ts有一个名为playerBullets的变量,需要在玩家每次射击时更新HTML5画布游戏TypeScript中的事件,typescript,Typescript,我正在开发一款HTML5画布空间入侵者游戏,希望从我的玩家类射击方法(在我的gameObject模块文件中)接收game.ts类中的事件game.ts有一个名为playerBullets的变量,需要在玩家每次射击时更新 module GameObjects { // Class export class Player { color: string = "#00A"; x: number = 50; y: number = 2
module GameObjects {
// Class
export class Player {
color: string = "#00A";
x: number = 50;
y: number = 270;
width: number = 20;
height: number = 30;
constructor () {
}
draw(canvas) {
canvas.fillStyle = this.color;
canvas.fillRect(this.x, this.y, this.width, this.height);
}
shoot() {
// Sound.play("shoot");
var bulletPosition = this.midpoint();
playerBullets.push(Bullet({
speed: 5,
x: bulletPosition.x,
y: bulletPosition.y
}));
};
midpoint() {
return {
x: this.x + this.width / 2,
y: this.y + this.height / 2
};
};
explode() {
// this.active = false;
// Extra Credit: Add an explosion graphic and then end the game
};
};
}
还有游戏。ts:
class game {
constructor () {
}
var playerBullets: Array = new Array[40];
FPS: number = 30;
有什么想法吗
如果我在纯js中这样做的话,将很容易使所有内容都成为全局性的,而不需要事件,但这将很难维护。像在另一种支持事件的oo语言(如c#)中那样处理它。在player中创建事件操作并在Main.ts中订阅 例如,在播放器中添加一个方法成员:
public OnShoot: Function;
然后在您的拍摄方法中添加以下行:
if(OnShoot) {
OnShoot(new Bullet({
speed: 5,
x: bulletPosition.x,
y: bulletPosition.y
}));
}
然后在Main.ts中,创建播放器后,只需注册它的OnShoot。例如:
var player = new GameObjects.Player();
player.OnShoot = function(bullet: Bullet) {
playerBullets.push(bullet);
}
希望这有帮助
注意:您总是可以通过事件监听器执行“真正的”基于事件的实现(JQuery对此有很好的设置),但是对于您的实现来说,一个可订阅函数就足够了。另外,我觉得它更合适。像处理其他支持事件的oo语言(如c#)一样处理它。在player中创建事件操作并在Main.ts中订阅 例如,在播放器中添加一个方法成员:
public OnShoot: Function;
然后在您的拍摄方法中添加以下行:
if(OnShoot) {
OnShoot(new Bullet({
speed: 5,
x: bulletPosition.x,
y: bulletPosition.y
}));
}
然后在Main.ts中,创建播放器后,只需注册它的OnShoot。例如:
var player = new GameObjects.Player();
player.OnShoot = function(bullet: Bullet) {
playerBullets.push(bullet);
}
希望这有帮助
注意:您总是可以通过事件监听器执行“真正的”基于事件的实现(JQuery对此有很好的设置),但是对于您的实现来说,一个可订阅函数就足够了。另外,我觉得它更合适。那么这个速度为5的项目符号是如何从项目符号类player.OnShoot=function(bullet:bullet)中的方法返回的{如果(OnShoot)为了确保某些东西已绑定到处理程序,您不想尝试执行未定义的函数(只是在使用前检查的良好实践)。其次,player shoot方法不会返回新的项目符号,而是将其传递到OnShoot方法。这个项目符号的速度是:5,如何从bullet类player.OnShoot=函数(bullet:bullet){如果(OnShoot)中的方法返回为了确保某些内容已绑定到处理程序,您不希望尝试执行未定义的函数(只是在使用前检查的良好实践)。其次,player shot方法不会返回新的项目符号,而是将其传递到onshot方法。