如何找到直线上两个给定点之间的坐标(JavaScript)? [英] How can you find the coordinates between two given points on a straight line(JavaScript)?

查看:600
本文介绍了如何找到直线上两个给定点之间的坐标(JavaScript)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一条直线上获得2个给定点之间的所有x,y,z坐标.我需要能够在JavaScript中执行此操作,以检查弹丸是否在我的游戏中发生碰撞.

I want to get all the x,y,z coordinates between 2 given points, on a straight line. I need to be able to do this in JavaScript for checking whether a projectile collides in my game.

例如,

点1:(0,0,0) 点2:(2,2,2) -> 0,0,0-1,1,1,2,2,2

Point 1: (0,0,0) Point 2: (2,2,2) -> 0,0,0 - 1,1,1, 2,2,2

编辑,这里是丢失者的有效代码.

Edit, here is working code for anybody who is lost.

def ROUND(a):

return int(a + 0.5)

def drawDDA(x1,y1,z1,x2,y2,z2):

def drawDDA(x1,y1,z1,x2,y2,z2):

x,y,z = x1,y1,z1

length = (x2-x1) if (x2-x1) > (y2-y1) else (y2-y1) if (y2-y1) > (z2-z1) else (z2-z1)

dx = (x2-x1)/float(length)

dy = (y2-y1)/float(length)

dz = (z2-z1)/float(length)

print (ROUND(x),ROUND(y),ROUND(z))

for i in range(length):

    x += dx
    z += dz
    y += dy

    print(ROUND(x),ROUND(y),ROUND(z)) 

drawDDA(0,1,2,10,11,12)

drawDDA(0,1,2,10,11,12)

推荐答案

您当前的方法将需要处理2D象限中的象限和3D情况中的八象限,这很麻烦.如果改用 DDA (非常相似),您将摆脱它.所以:

Your current approach will need to deal with quadrants in 2D and octants in 3D which is pain in the ass. if you use DDA instead (which is very similar) you will get rid of that. So:

P(t) = P0 + t*(P1-P0)
t=<0.0,1.0

这也称为线性插值.由于两个端点P0,P1之间有无限数量的点P(t),所以我假设您只需要整数(代表PIXELS),因此您需要选择"c2>",且步长为像素",并舍入或限制P(t).很简单:

This is also called Linear Interpolation. As there are infinite number of points P(t) between your two endpoints P0,P1 I assume you want just integer ones (representing PIXELS) so you need to select t with single "pixel" step and round or floor the coordinates of P(t). That is simple:

dP = abs(P1-P0)
dt = 1.0/max(dP.x,dP.y,dP.z)

这称为行栅格化,也可以将其移植到整数算术中,而无需使用浮点数.移植的版本如下所示:

this is called line rasterization and can be also ported to integer arithmetics without the need for floats. The ported version looks like this:

dP = abs(P1-P0)
T = max(dP.x,dP.y,dP.z)
t = {0,1,2,...,T}
P(t) = P0 + (P1-P0)*t/T

甚至可以通过在内部循环中通过简单的条件增量/减量交换*t/T来改善此情况,

And even this can be improved by exchanging the *t/T by simple conditional increment/decrement inside loop like this:

还有其他类似的算法,例如布雷森纳姆(Bresenham),但DDA在现代体系结构上速度更快,并且更简单,更容易扩展到任何维度.

There are also different algorithms like Bresenham for this but DDA is faster on modern architectures and also much simpler and easily expandable to any dimensionality.

这篇关于如何找到直线上两个给定点之间的坐标(JavaScript)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆