在 JavaScript Canvas 中沿线移动点 [英] Moving a Point Along a Line in JavaScript Canvas

查看:28
本文介绍了在 JavaScript Canvas 中沿线移动点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一条线的坐标(25,35 45,65, 30,85 - 这将是一条两部分的线).我需要每帧以恒定距离沿该线移动一个点(汽车).我该怎么做?

Let's say that I have the coordinates of a line (25,35 45,65, 30,85 - It would be a two part line). I need to move a point (car) along that line at a constant distance every frame. How can I do this?

推荐答案

考虑行 (25,35 45,65).从头到尾的向量是 (20, 30).要在那个方向移动一个点 (x,y),我们可以添加那个向量:

Consider the line (25,35 45,65). The vector from the beginning to the end is (20, 30). To move a point (x,y) in that direction, we could just add that vector:

V = (20, 30)(x,y) => (x+20, y+30).

V = (20, 30) (x,y) => (x+20, y+30).

如果我们从行的开头开始,我们就会到达结尾.但这一步太大了.我们想要更小但方向相同的东西,所以我们将向量乘以 0.1:

If we start at the beginning of the line, we'll arrive at the end. But that's too big a step. We want something smaller but in the same direction, so we multiply the vector by, say, 0.1:

V = (2, 3)(x,y) => (x+2, y+3) => (x+4, y+6) => ...

V = (2, 3) (x,y) => (x+2, y+3) => (x+4, y+6) => ...

归一化很方便,也就是让它的长度为1,我们通过除以它的长度来实现:

It's convenient to normalize, that is to make its length 1, which we do by dividing by its length:

V => V/|V|= (2,3)/sqrt(22 + 32) = (7.21, 10.82)

V => V/|V| = (2,3)/sqrt(22 + 32) = (7.21, 10.82)

然后你可以把它乘以你想要的任何步长.

Then you can just multiply that by whatever step size you want.

这篇关于在 JavaScript Canvas 中沿线移动点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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