简体   繁体   English

如何在 JavaScript 中沿某个角度移动对象?

[英]How can I move objects along a certain angle in JavaScript?

So I have an integer variable, and it's supposed to represent the angle that I want this object to move along, it looks like this:所以我有一个 integer 变量,它应该代表我希望这个 object 移动的角度,它看起来像这样:

const Degree = 90

Now obviously we need a object to move in this angle, so we can easily draw this to the canvas.现在显然我们需要一个 object 以这个角度移动,所以我们可以很容易地把它画到 canvas 上。

const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
// ...
ctx.beginPath();
ctx.arc(0, 0, 3.75, 0, 2 * Math.PI);
ctx.fillStyle = 'black';
ctx.fill();

How can I move this little circle along the axis I set in the degrees variable?我怎样才能沿着我在degrees变量中设置的轴移动这个小圆圈?

One common option for learning about canvas animations is using Algebra (sin/cos) to calculate the distance to add for each value.了解 canvas 动画的一个常见选项是使用代数 (sin/cos) 来计算要为每个值添加的距离。 Here is a very simple, non interactive example.这是一个非常简单的非交互式示例。

 const canvas = document.createElement("canvas"); canvas.height = 400; canvas.width = 400; const ctx = canvas.getContext("2d"); document.body.appendChild(canvas); var circle = new MovableCircle(); setInterval(function() { // This is our "game loop", the easiest way, not the best way ctx.beginPath(); ctx.clearRect(0, 0, canvas.width, canvas.height) circle.draw(); circle.x += Math.cos(DegreesToRadians(circle.direction)) * circle.speed; circle.y += Math.sin(DegreesToRadians(circle.direction)) * circle.speed; }, 1000 / 60) function MovableCircle() { this.x = 10; this.y = 10; this.speed = 1; this.direction = 45; this.draw = () => { ctx.arc(this.x, this.y, 20, 0, 2 * Math.PI); ctx.fillStyle = 'black'; ctx.fill(); } } function DegreesToRadians(degrees) { return degrees * (Math.PI / 180); }

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

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