저는 학교용 Jquery 게임을 구축하는 중이며 함수 끝에 setTimeout ()을 추가하여 메서드가 실행될 때 create () 자신을 회수하려고합니다 (addEnemySpeed가 무작위로 생성되어 매번 변경됨) 그러나 메서드가 호출되어 한 번만 실행되고 (smallEnemy.create ()) 작동하지 않지만 자체를 회수하지 않습니까? 나는 이것이 내 부분에 대한 단순한 감독이기를 바라고 있습니까 ?? 도움을 주셔서 미리 감사드립니다. 건배.
// OBSTACLE OBJECT CONSTRUCTOR //
function Obstacle(type, className, speed, startHealth, currentHealth, damageCause) {
this.type = type;
this.className = className;
this.speed = speed;
this.endX = -160;
this.startHealth = startHealth;
this.currentHealth = currentHealth;
this.damageCause = damageCause;
this.create = function(type, endX, speed) {
type = this.type;
endX = this.endX;
speed = this.speed;
var $obstacle = $('<div>');
// if the obstacle is a enemy add enemies class
if (type == 'smallEnemy' || type == 'bigEnemy') {
$obstacle.addClass('enemies');
}
// add correct class name
$obstacle.addClass(type);
// add obstacle to playground
$('#playGround').append($obstacle);
// animate obstacle down x axis remove if hits destination
$obstacle.transition({
x: endX
}, speed, 'linear', function() {
$(this).remove();
});
setTimeout(this.create,addEnemySpeed);
};
}
smallEnemy.create()
이것은 프로토 타입이 아닙니다. 오히려 생성자입니다. 새로운 장애물을 만들 때 전화하고 싶을 것입니다.var foo = new Obstacle(...);
function Obstacle(type, className, speed, startHealth, currentHealth, damageCause) {
// private vars
var timeout,
endX = -160;
// private methods
function create(addEnemySpeed) {
var $obstacle = $('<div>');
// if the obstacle is a enemy add enemies class
if (type == 'smallEnemy' || type == 'bigEnemy') {
$obstacle.addClass('enemies');
}
// add correct class name
$obstacle.addClass(type);
// add obstacle to playground
$('#playGround').append($obstacle);
// animate obstacle down x axis remove if hits destination
$obstacle.transition({x: endX}, speed, 'linear', function() {
$(this).remove();
});
timeout = setTimeout(create, addEnemySpeed);
}
// I added this method so you can stop spawning this obstacle if you want
function stop() {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
}
// public api (exports)
this.type = type;
this.className = className;
this.speed = speed;
this.startHealth = startHealth;
this.currentHealth = currentHealth;
this.damageCause = damageCause;
this.create = create;
this.stop = stop;
}
알았어 지금 사용하자
var smallEnemy = new Obstacle(...);
// Spawn a new enemy of this type ever 5 seconds
// Don't forget to pass addEnemySpeed
// (addEnemySpeed was undefined in your code)
smallEnemy.create(5000);
선택 사항 :stop
스폰을 중지하고 싶을 때 호출
smallEnemy.stop();
참고로 몇 가지 기본값을 정의하고 생성자에 객체를 전달하는 것을 고려할 수 있습니다. 이렇게하면 6 개의 순서가 지정된 인수를 생성자에 전달할 필요가 없습니다.
new Obstacle({type: "foo", speed: 100});
개체에 설정되지 않은 모든 키에 대해 기본값으로 대체합니다. 이것이 당신을위한 선택이라면 당신은 나보다 더 잘 알 것입니다. 내가 언급 할 줄 알았는데.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다