Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rotation fixes #40

Merged
merged 9 commits into from
Mar 13, 2019
Merged
24 changes: 18 additions & 6 deletions src/Particle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,16 @@ import { randomRange, randomInt, degreesToRads } from './utils'
import { IConfettiOptions } from './Confetti'

export enum ParticleShape {
Cirlce = 0,
Circle = 0,
Square,
Strip,
}

enum RotationDirection {
Positive = 1,
Negative = -1,
}

export default class Particle {
constructor(context: CanvasRenderingContext2D, getOptions: () => IConfettiOptions, x: number, y: number) {
this.getOptions = getOptions
Expand All @@ -24,6 +29,7 @@ export default class Particle {
this.angularSpin = randomRange(-0.2, 0.2)
this.color = colors[Math.floor(Math.random() * colors.length)]
this.rotateY = randomRange(0, 1)
this.rotationDirection = randomRange(0, 1) ? RotationDirection.Positive : RotationDirection.Negative
}
context: CanvasRenderingContext2D
radius: number
Expand All @@ -37,7 +43,9 @@ export default class Particle {
angle: number
angularSpin: number
color: string
// Actually used as scaleY to simulate rotation cheaply
rotateY: number
rotationDirection: RotationDirection
getOptions: () => IConfettiOptions

update() {
Expand All @@ -54,11 +62,15 @@ export default class Particle {
this.vx += wind
this.vx *= friction
this.vy *= friction
if(this.rotateY < 1) {
this.rotateY += 0.1
} else {
this.rotateY = -1
if(this.rotateY >= 1 && this.rotationDirection === RotationDirection.Positive) {
this.rotationDirection = RotationDirection.Negative
} else if(this.rotateY <= -1 && this.rotationDirection === RotationDirection.Negative) {
this.rotationDirection = RotationDirection.Positive
}

const rotateDelta = 0.1 * this.rotationDirection

this.rotateY += rotateDelta
this.angle += this.angularSpin
this.context.save()
this.context.translate(this.x, this.y)
Expand All @@ -75,7 +87,7 @@ export default class Particle {
drawShape.call(this, this.context)
} else {
switch(this.shape) {
case ParticleShape.Cirlce: {
case ParticleShape.Circle: {
this.context.beginPath()
this.context.arc(0, 0, this.radius, 0, 2 * Math.PI)
this.context.fill()
Expand Down
2 changes: 1 addition & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ export function rectIntersect(r0: IRect, r1: IRect) {
}

export function degreesToRads(degrees: number) {
return degrees / (180 * Math.PI)
return degrees * Math.PI / 180
}

export function radsToDegrees(radians: number) {
Expand Down