使用ts写物体绕圆运动算法
时间: 2023-10-26 16:21:44 浏览: 42
以下是使用 TypeScript 实现物体绕圆运动的算法:
```typescript
class Circle {
constructor(public x: number, public y: number, public radius: number) {}
// 获取圆上某个点的坐标
getPoint(angle: number): [number, number] {
const x = this.x + this.radius * Math.cos(angle);
const y = this.y + this.radius * Math.sin(angle);
return [x, y];
}
}
class MovingObject {
private angle: number = 0;
private speed: number = 0.01;
constructor(public circle: Circle, public radius: number) {}
// 更新物体位置
update() {
this.angle += this.speed;
const [x, y] = this.circle.getPoint(this.angle);
this.radius += 0.1; // 可以控制物体沿圆周移动的速度
// 将物体位置更新为圆上的点
this.circle.x = x;
this.circle.y = y;
}
}
```
使用示例:
```typescript
const canvas = document.getElementById("canvas") as HTMLCanvasElement;
const ctx = canvas.getContext("2d") as CanvasRenderingContext2D;
const circle = new Circle(canvas.width / 2, canvas.height / 2, 100);
const movingObject = new MovingObject(circle, 0);
function render() {
// 清空画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制圆
ctx.beginPath();
ctx.arc(circle.x, circle.y, circle.radius, 0, 2 * Math.PI);
ctx.stroke();
// 绘制物体
ctx.beginPath();
ctx.arc(circle.x + movingObject.radius, circle.y, 10, 0, 2 * Math.PI);
ctx.fill();
// 更新物体位置
movingObject.update();
// 循环调用 render 函数
requestAnimationFrame(render);
}
render();
```
在示例中,我们首先创建了一个圆和一个物体,然后在 `render` 函数中循环绘制圆和物体。在每次循环中,我们调用 `movingObject.update()` 方法更新物体位置,然后重新绘制圆和物体。这样就可以实现物体绕圆运动的效果。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)