2014-03-19 112 views
3

我有一個球和一個棍子(用於檯球遊戲)。創建矢量和碰撞

首先將球放置在桌子的某個位置。點擊球時,球杆出現,這樣我們就可以通過點擊球來確定球杆的放置角度(點擊時我們確定鼠標相對於球的中心的角度,並將球杆放在那個角度上球)。

所以現在棒也在桌子上。現在,我只沿着該角度拖動棍子,如果以不同於初始角度的角度拖動它,則返回false。

在拖動結束時,我正在計算杆的移動距離,杆返回到與球接觸的初始位置。然後,我試圖根據棒的角度和由棒移動的距離移動球。

球在這裏移動,但沒有關於這些中的任何一個。這已經成爲我的問題,我已經更新了小提琴here

strikerGroup.on('dragend', function() { 
    var strikerLastPos = strikerGroup.getAbsolutePosition(); 
    strikerGroup.setPosition(initStrikerGrpX, initStrikerGrpY); 
    striker.speedX = striker.speedY = 2; 
    var strikerGrpDistMoved = Math.sqrt(((strikerLastPos.x - strikerGroup.getAbsolutePosition().x) * (strikerLastPos.x - strikerGroup.getAbsolutePosition().x)) + ((strikerLastPos.y - strikerGroup.getAbsolutePosition().y) * (strikerLastPos.y - strikerGroup.getAbsolutePosition().y))); 
    var newX = striker.getX() + (Math.cos(theta) * strikerGrpDistMoved); 
    var newY = striker.getY() - (Math.sin(theta) * strikerGrpDistMoved); 
    var strikerMove = new Kinetic.Tween({ 
     node: striker, 
     duration: 5, 
     x: newX, 
     y: newY, 
     easing: Kinetic.Easings.EaseInOut 
    }); 
    console.log(striker.getX()); 
    strikerMove.play(); 
    layer.batchDraw(); 
    // strikerGroup striked the striker!!!! 
}); 

回答

3

您計算檯球棒的角度把球像這樣:

var dx = ballX - stickX; 
var dy = ballY - stickY; 
var angle = Math.atan2(dy,dx); 

然後你可以沿着移動球像這樣的角度:

var newBallX = ballX + desiredRollDistance * Math.cos(angle); 
var newBallY = ballY + desiredRollDistance * Math.sin(angle); 

您希望的滾動距離將基於棒遠離球被拉回遠處。

棒被拉回越遠==球進一步移動。

可以計算出球像這樣從棒的距離:

var dx = ballX - stickX; 
var dy = ballY - stickY; 
var lengthFromStickToBall = Math.sqrt(dx*dx+dy*dy); 

這裏是一個演示:http://jsfiddle.net/m1erickson/B6K9z/

+0

謝謝。 它worked..Great幫助。 – Adidev