-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrr.js
More file actions
104 lines (104 loc) · 2.68 KB
/
rr.js
File metadata and controls
104 lines (104 loc) · 2.68 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
"use strict";
// Get the canvas element and context
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
// Define the player class
class Player {
constructor(x, y, width, height, color, speed, dx = 0, dy = 0) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.color = color;
this.speed = speed;
this.dx = dx;
this.dy = dy;
this.friction = 0.9; // Friction factor to simulate momentum
}
draw() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
update() {
this.dx *= this.friction;
this.dy *= this.friction;
this.x += this.dx;
this.y += this.dy;
// Prevent the player from going out of bounds
if (this.x < 0)
this.x = 0;
if (this.y < 0)
this.y = 0;
if (this.x + this.width > canvas.width)
this.x = canvas.width - this.width;
if (this.y + this.height > canvas.height)
this.y = canvas.height - this.height;
}
accelerate(ax, ay) {
this.dx += ax;
this.dy += ay;
}
}
// Create two player objects
const player1 = new Player(50, 50, 50, 50, 'blue', 5);
const player2 = new Player(200, 50, 50, 50, 'red', 5);
// Key handling
const keys = {
ArrowLeft: false,
ArrowRight: false,
ArrowUp: false,
ArrowDown: false,
a: false,
d: false,
w: false,
s: false
};
window.addEventListener('keydown', (e) => {
keys[e.key] = true;
});
window.addEventListener('keyup', (e) => {
keys[e.key] = false;
});
function updatePlayers() {
// Acceleration factor
const acceleration = 0.5;
// Update player 1 (WASD)
if (keys['a'])
player1.accelerate(-acceleration, 0);
if (keys['d'])
player1.accelerate(acceleration, 0);
if (keys['w'])
player1.accelerate(0, -acceleration);
if (keys['s'])
player1.accelerate(0, acceleration);
// Update player 2 (Arrow Keys)
if (keys['ArrowLeft'])
player2.accelerate(-acceleration, 0);
if (keys['ArrowRight'])
player2.accelerate(acceleration, 0);
if (keys['ArrowUp'])
player2.accelerate(0, -acceleration);
if (keys['ArrowDown'])
player2.accelerate(0, acceleration);
}
// Game loop
function clear() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
function update() {
updatePlayers();
player1.update();
player2.update();
}
function draw() {
player1.draw();
player2.draw();
}
function gameLoop() {
clear();
update();
draw();
requestAnimationFrame(gameLoop);
}
// Start the game loop
gameLoop();