简体   繁体   中英

How to give the illusion of rotation to a moving ball

 //draw method
 draw() {
     //draw the ball
     ctx.beginPath();
     ctx.arc(this.xPos, this.yPos, this.radius, 0, 2 * Math.PI), false;
     ctx.moveTo(this.xPos, this.yPos);
     var i;
     //use a for loop 
     for (i = 1; i < 8; i++) {
         var x = this.radius * Math.cos(i * 2 / 7 * Math.PI) + this.xPos;
         var y = this.radius * Math.sin(i * 2 / 7 * Math.PI) + this.yPos;
         ctx.lineTo(x, y);
         ctx.moveTo(this.xPos, this.yPos);
     }

     ctx.lineTo(this.xPos, this.yPos);
     ctx.fillStyle = "rgba(125, 125, 125, 1)";
     ctx.strokeStyle = "red";
     ctx.fill();
     ctx.stroke();
 }

I'm completely new to graphics programming, and I am wondering how I could use a rotate method to shift all the lines in the circle (created by the draw method) by a fixed amount of radians as it moves

here is an image of the output:

输出

There are more efficient ways to go about this, but they would require things like webgl or webgpu so just to get what you want going:

This is the 2D rotation matrix: 在此处输入图片说明

Add a theta parameter to your draw method and outside of the draw parameter increment it by a small amount like 0.001 on each iteration of a loop (remember to clear your canvas before drawing).

Then inside of your method, calculate the center C of your circle. The formula to rotate ANY shape round its centroid C 'is:

R(theta) * (S - C) + C

Where S is the set of all points in your shape and R(theta) is the rotation matrix evaluated at theta.

In other words, for every pair of (x, y) coordinates in the cartwheel, you first subtract the center, then you multiply the resulting vector <x, y> by the rotation matrix FROM THE LEFT (R * V), the final vector <x', y'> represents the rotated shape.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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