-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgrass.js
More file actions
83 lines (68 loc) · 2.59 KB
/
grass.js
File metadata and controls
83 lines (68 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
class GrassBlade {
constructor(ctx, x, stemLength, tipLength) {
this.ctx = ctx;
this.x = x;
this.stemLength = stemLength;
this.tipLength = tipLength;
}
draw(y, swayAmplitude, grassSwayAngle, interp) {
// Interpolate the sway angle for smoother motion
const interpolatedSwayAngle = grassSwayAngle + (interp * 0.05);
// Sway the bottom part of the blade (stem)
const swayStem = Math.sin(interpolatedSwayAngle + this.x * 0.1) * swayAmplitude;
// Calculate the tip's sway based on the stem's sway
const swayTip = Math.sin(interpolatedSwayAngle + this.x * 0.15) * swayAmplitude * 0.7;
// Draw the stem
const stemEndX = this.x + swayStem;
const stemEndY = y - this.stemLength;
this.ctx.beginPath();
this.ctx.moveTo(this.x, y);
this.ctx.lineTo(stemEndX, stemEndY);
this.ctx.stroke();
// Draw the tip
const tipEndX = stemEndX + swayTip;
const tipEndY = stemEndY - this.tipLength;
this.ctx.beginPath();
this.ctx.moveTo(stemEndX, stemEndY);
this.ctx.lineTo(tipEndX, tipEndY);
this.ctx.stroke();
}
}
class GrassPatch {
constructor(ctx, xStart, xEnd, y, stemLength, tipLength, bladeSpacing, swayAmplitude) {
this.ctx = ctx;
this.y = y;
this.swayAmplitude = swayAmplitude;
this.grassSwayAngle = 0;
this.blades = [];
for (let i = xStart; i < xEnd; i += bladeSpacing) {
const variableStemLength = stemLength + (Math.random() * 10 - 5);
const variableTipLength = tipLength + (Math.random() * 5 - 2.5);
this.blades.push(new GrassBlade(ctx, i, variableStemLength, variableTipLength));
}
}
draw(interp) {
this.ctx.strokeStyle = "#3f9b0b";
this.ctx.lineWidth = 2;
this.blades.forEach(blade => {
blade.draw(this.y, this.swayAmplitude, this.grassSwayAngle, interp);
});
}
update(deltaTime) {
this.grassSwayAngle += deltaTime * 4;
}
}
// Function to draw the static grass gradient background
function drawGrass() {
ctx.save();
// Create a green gradient for the grass
const grad = ctx.createLinearGradient(0, canvas.height - 70, 0, canvas.height);
grad.addColorStop(0, "#3f9b0b"); // Light green at the top
grad.addColorStop(1, "darkgreen"); // Dark green at the bottom
ctx.fillStyle = grad;
// Draw the rectangle that represents the grass
ctx.beginPath();
ctx.rect(0, canvas.height - 70, canvas.width, 70);
ctx.fill();
ctx.restore();
}