2016-07-06 53 views
0

實施例移動體:/與球60公里每小時的速度發射大炮libgdx Box2D的身體 - 如何通過給定的力或速度,距離和時間

給定:(60 KPH) 距離= 60公里, 時間=1小時

enter image description here

Libgdx:遊戲世界

// Given that I am using 1/45.0f step time, the rest iteration velocity 6 and position 2 
// Given that 60.00012 kilometres per hour = 16.6667 metres per second 
float speed = 16.6667f; // 16.6667 metres per second 
Vector2 bulletPosition = body.getPosition(); 
Vector2 targetPosition = new Vector2(touchpoint.x touchpoint.y); 

Vector2 targetDirection = targetPosition.cpy().sub(bulletPosition).scl(speed); 

問題:但我的問題是炮彈沒有以我想要的速度移動,我該如何記錄車身速度,以便檢查速度是否正確。我只注意到它是錯誤的,因爲炮彈運動得慢,可想而知每小時60公里

PS:假設上面的圖片寬度爲5米,高度爲3米

body.setLinearVelocity(targetDirection.scl(deltaTime)); 

問題2:我不知道我怎麼計算由給定的速度和步發力

// Given that F = ma 
Vector2 acceleration = ??? 
float mass = body.getMass(); 
Vector2 force = ??? 
body.applyForces(force); 

回答

1

在Box2d中,不是直接施加力而是施加作用力一段時間的衝擊,這會有效地產生近乎瞬時的加速度。計算你的衝動只是一些物理學。

首先我們定義了一些變量,F是牛頓的力,a是加速,I是衝動(這是我們要計算在Box2D的申請),u是初始速度(米每秒),v是最終速度和t是以秒爲單位的時間。

用牛頓定律,我們有開始加速的定義:

現在,我們可以計算出衝動:

在你的情況,u是0,因爲炮彈最初是靜止的,所以它歸結爲:

就是這樣!所以,在你的代碼中,你可以對炮彈施加一個等於質量乘以所需速度的衝量。以下代碼還包含了如何計算touchPoint的方向。

E.G:

float mass = body.getMass(); 
float targetVelocity = 16.6667f; //For 60kmph simulated 
Vector2 targetPosition = new Vector2(touchpoint.x, touchpoint.y); 

// Now calculate the impulse magnitude and use it to scale 
// a direction (because its 2D movement) 
float impulseMag = mass * targetVelocity; 

// Point the cannon towards the touch point 
Vector2 impulse = new Vector2(); 

// Point the impulse from the cannon ball to the target 
impulse.set(targetPosition).sub(body.getPosition()); 

// Normalize the direction (to get a constant speed) 
impulse.nor(); 

// Scale by the calculated magnitude 
impulse.scl(impulseMag); 

// Apply the impulse to the centre so there is no rotation and wake 
// the body if it is sleeping 
body.applyLinearImpulse(impulse, body.getWorldCentre(), true); 

編輯:響應於該評論:

的歸一化矢量爲單位長度矢量這意味着它具有的尺寸爲1(不管它是在該角)。可視說明(維基百科):

enter image description here

兩種載體d1d2是單位矢量,因此被稱爲歸一化。在Vector2中,nor函數通過將矢量保持在相同的角度而使其矢量歸一化,但將其賦值爲1。正如下面的圖表顯示(藍色是原始載體和綠色是歸一化後):

enter image description here

你的遊戲,這點是爲了讓炮彈行進以相同的速度播放器是否觸及屏幕距炮彈非常近或非常遠,所有重要的是與大炮的角度。

+0

嗨@BasimKhajwal感謝您的乾淨,明確,可以理解的答案!施加衝擊後,方向稍有不同。例如,當我以30度角度觸摸屏幕時,球在32度上移動,但這不準確。奇怪的行爲,我仍然對Vector2的使用感到困惑。我仍然不明白它的目的。 – ronscript

相關問題