0

我正在學習使用javascript的物理引擎的基礎知識,並且希望引擎和遊戲數據都保存在一個對象中,但一直無法使用'this'關鍵字遞歸調用draw函數來動畫場景時。我可以成功地調用單獨的繪圖函數,但不會那麼容易實現多個對象來製作動畫window.requestAnimationFrame使用對象和這個關鍵字

這裏有一個簡單的codepen帶有一個工作測試平臺。

這裏是頁

<!doctype html> 
<html> 

<head> 

<style type="text/css"> 

    #obj{ 
     width: 50px; 
     height: 200px; 
     background: red; 
     position: absolute; 
     left: 100px; 
     bottom: 200px; 
    } 

    #ground{ 
     width: 100%; 
     height: 200px; 
     background: #222; 
     position: absolute; 
     bottom: 0; 
     left: 0; 
    } 

</style> 


</head> 

<body> 

<div id="content"> 

<section> 
    <button onclick="draw()">draw()</button><br> 
    <button onclick="obj.draw()">obj.draw()</button> 
</section> 

<article> 

    <div id="obj"></div> 
    <div id="ground"></div> 

</article> 

</div> <!-- END CONTENT --> 

</body> 

<script type="text/javascript"> 

var obj = { 
    // variables 
    id: 'obj', 
    width: 50, 
    height: 200, 
    angle: 30, 
    speed: 20, 
    acceleration: 4/60, 
    deceleration: 2/60, 
    moving: false, 
    jumping: false, 
    // Get methods 
    x: function(){return parseInt(window.getComputedStyle(document.getElementById(this.id)).left)}, 
    y: function(){return parseInt(window.getComputedStyle(document.getElementById(this.id)).bottom)}, 
    // engine methods 
    scale_x: function(){return Math.cos((this.angle * Math.PI)/180)}, 
    scale_y: function(){return Math.sin((this.angle * Math.PI)/180)}, 
    velocity_x: function(){return this.speed * this.scale_x()}, 
    velocity_y: function(){return this.speed * this.scale_y()}, 
    cx: function(){return this.x() + this.width}, 
    cy: function(){return this.y() + this.height}, 
    // set methods 
    setAngle: function(val){this.angle = val}, 
    setAcceleration: function(val){this.acceleration = val/60}, 
    setDeceleration: function(val){this.deceleration = val/60}, 
    setSpeed: function(val){this.speed = val}, 
    setMoving: function(val){this.moving = val}, 
    setJumping: function(val){this.jumping = val}, 
    draw: function(){ 
     document.getElementById(this.id).style.left = (this.speed++) + 'px'; 
     window.requestAnimationFrame(this.draw); 
    } 
} 

function draw(){ 
    document.getElementById(obj.id).style.left = (obj.speed++) + 'px'; 
     window.requestAnimationFrame(draw); 
} 

</script> 

</html> 

感謝您的幫助,

安德魯

回答

1

觀察,你撥打obj.draw爲:

<button onclick="obj.draw() 

第一次obj.draw是所謂的上下文不同於它被調用時的上下文多次,作爲repaint之前的回調函數。

因此,請嘗試將這個保存在回調函數範圍之外的變量中。

喜歡的東西:

var obj = {  
    //... 

    draw: function() { 
     var sender = this; 
     var draw = function() { 
      document.getElementById(sender.id).style.left = (sender.speed++) + 'px'; 
      window.requestAnimationFrame(draw); 
     } 
     draw(); 
    } 
} 

這裏是如何做到這一點看起來像一個updated demo

+0

明智的感謝解釋,我確實看到有關此問題的其他線程,但這是最好的例子 – synthet1c