简体   繁体   English

通过距离和摩擦计算速度

[英]Calculate speed by distance and friction

I am writing a game in Javascript, Canvas, HTML5, and I just found a big problem, related to advanced maths. 我正在用Javascript,Canvas,HTML5编写游戏,我发现了一个与高级数学相关的大问题。 The game is in flat 2D, so you see the world from over. 游戏是平面2D,所以你可以看到世界。 That means there is no gravity, only friction. 这意味着没有重力,只有摩擦力。

CODE: 码:

var friction = 0.97

var target = {
  x: 70,
  y: 90,
}

var ball = {
  x: 10,
  y: 20,
  vx: 0,
  vy: 0,
}
var dx = ball.x - target.x
var dy = ball.y - target.y
var angle = Math.atan2(dy, dx)
var dist = Math.sqrt(dx * dx + dy * dy) // <--- AS FAR AS I'VE COME
var speed = ??? // <--- HERE IS THE PROBLEM
ball.vx = Math.cos(angle) * speed
ball.vy = Math.sin(angle) * speed

function update() {
  ball.vx *= friction
  ball.vy *= friction
  ball.x += ball.vx
  ball.y += ball.vy

  // Drawing and other unneccesary things to involve here

  window.requestAnimationFrame(update)
}

update()

So, my question is: How do I calculate the speed in the section where I create the ball, to make the ball stop at exactly the targets x and y position? 所以,我的问题是:如何计算我创建球的部分的速度,使球停在目标x和y位置? As far as I've come I've only calculated the starting distance between the ball and the targets position.. Soo, any ideas? 就我而言,我只计算了球与目标位置之间的起始距离..那么,任何想法? Is there an equation for this? 有这个等式吗?

So you want the sum for i from 1 to ∞ over the term (speed × friction i ), and you want the result to equal dist. 因此,您希望i的总和从1到∞超过项(速度×摩擦力i ),并且您希望结果等于dist。 This is an infinite geometric series , the limit of which is speed×friction/(1 − friction). 这是一个无限的几何系列 ,其极限是速度×摩擦力/(1 - 摩擦力)。

无穷和的公式

So simply solve the equation for speed, and you obtain: 所以简单地解决速度等式,你得到:

解决速度公式

speed = (1/friction - 1)*dist

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM