I'm trying to make a racing game, and my first step was to try out making the car and getting it to move a bit. Unfortunately, it isn't working, as nothing is showing up on the canvas, not the rectangle nor the car. Any ideas (of course you have ideas)? Sorry if the code isn't formatted correctly, I joined this site today.
HTML:
<!doctype html>
<html lang="en">
<head>
<title>Ball</title>
<script src="http://code.jquery.com/jquery-git2.js"></script>
</head>
<body>
<center>
<canvas id="gameCanvas" width="500" height="500" style="border:5px solid green"></canvas>
<script src="js/Game.js"></script>
</center>
</body>
</html>
JS:
window.onload = function() {
var x = 0;
var y = 0;
var speed = 5;
var angle = 0;
var mod = 0;
var canvas = $('#gameCanvas')[0].getContext('2d');
var context = gameCanvas.getContext('2d');
var car = new Image();
car.src = "Gamecar.png";
window.addEventListener("keydown", keypress_handler, false);
window.addEventListener("keyup", keypress_handler, false);
var moveInterval = setInterval(function() {
draw();
}, 30);
};
function render() {
context.clearRect(0, 0, width, height);
context.fillStyle = "rgb(200, 100, 220)";
context.fillRect(50, 50, 100, 100);
x += (speed * mod) * Math.cos(Math.PI / 180 * angle);
y += (speed * mod) * Math.sin(Math.PI / 180 * angle);
context.save();
context.translate(x, y);
context.rotate(Math.PI / 180 * angle);
context.drawImage(car, -(car.width / 2), -(car.height / 2));
context.restore();
}
function keyup_handler(event) {
if (event.keyCode == 87 || event.keyCode == 83) {
mod = 0;
}
}
function keypress_handler(event) {
console.log(event.keyCode);
if (event.keyCode == 87) {
mod = 1;
}
if (event.keyCode == 83) {
mod = -1;
}
if (event.keyCode == 65) {
angle -= 5;
}
if (event.keyCode == 68) {
angle += 5;
}
}
This is what you need for a start:
function draw() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "rgb(200, 100, 220)";
context.fillRect(50, 50, 100, 100);
x += (speed * mod) * Math.cos(Math.PI / 180 * angle);
y += (speed * mod) * Math.sin(Math.PI / 180 * angle);
context.save();
context.translate(x, y);
context.rotate(Math.PI / 180 * angle);
context.drawImage(car, -(car.width / 2), -(car.height / 2));
context.restore();
}
That is the original render function, but you use it as draw. Also, there were invalid width and height references inside, so I used canvas.width and canvas.height.
This is the progress so far: http://jsfiddle.net/qf47mb4k/
Added an existing car image here, so no more errors in the console: http://jsfiddle.net/qf47mb4k/2/
WASD keys are now working, but you need to clear the canvas on every frame to get what you expected.
After fixing your canvas and context objects (also removed jQuery):
var canvas = document.getElementById('gameCanvas');
var context = canvas.getContext('2d');
To get the brakes working, you need to fix your keyup handler:
window.addEventListener("keyup", keyup_handler, false);
Everything seems fine now: http://jsfiddle.net/qf47mb4k/4/. Enjoy driving the car!
Full Code / Working Example
var x = 0;
var y = 0;
var speed = 5;
var angle = 0;
var mod = 0;
var canvas = document.getElementById('gameCanvas');
var context = canvas.getContext('2d');
var car = new Image();
car.src = "http://images.clipartpanda.com/car-top-view-clipart-red-racing-car-top-view-fe3a.png";
window.addEventListener("keydown", keypress_handler, false);
window.addEventListener("keyup", keyup_handler, false);
var moveInterval = setInterval(function () {
draw();
}, 30);
function draw() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "rgb(200, 100, 220)";
context.fillRect(50, 50, 100, 100);
x += (speed * mod) * Math.cos(Math.PI / 180 * angle);
y += (speed * mod) * Math.sin(Math.PI / 180 * angle);
context.save();
context.translate(x, y);
context.rotate(Math.PI / 180 * angle);
context.drawImage(car, -(car.width / 2), -(car.height / 2));
context.restore();
}
function keyup_handler(event) {
if (event.keyCode == 87 || event.keyCode == 83) {
mod = 0;
}
}
function keypress_handler(event) {
console.log(event.keyCode);
if (event.keyCode == 87) {
mod = 1;
}
if (event.keyCode == 83) {
mod = -1;
}
if (event.keyCode == 65) {
angle -= 5;
}
if (event.keyCode == 68) {
angle += 5;
}
}
<canvas id="gameCanvas" width="500" height="500" style="border:5px solid green"></canvas>
Related
I want to resize a rotated shape without it drifting away. I'm aware that I need to adjust the shape coordinates depending on the rotation angle, but I can't seem to figure out the formula to do it.
This is what I've managed to do so far (https://jsfiddle.net/9o3vefym/1/)
<!DOCTYPE html>
<html>
<body style="margin: 0">
<canvas
id="canvas"
width="400"
height="400"
style="border: 1px solid #d3d3d3"
></canvas>
<script>
const canvas = document.getElementById("canvas");
const context = canvas.getContext("2d");
const rect = {
x: 100,
y: 100,
width: 50,
height: 50,
angle: 0
};
window.onkeydown = keyDown;
draw();
function keyDown(evt) {
if (evt.key == "ArrowRight") {
rect.width += 5;
}
if (evt.key == "ArrowLeft") {
rect.x -= 5;
rect.width += 5;
}
if (evt.key == "ArrowUp") {
rect.y -= 5;
rect.height += 5;
}
if (evt.key == "ArrowDown") {
rect.height += 5;
}
if (evt.key == "a") {
rect.angle -= (45 * Math.PI) / 180;
}
if (evt.key == "s") {
rect.angle += (45 * Math.PI) / 180;
}
draw();
}
function draw() {
context.setTransform(1, 0, 0, 1, 0, 0);
context.clearRect(0, 0, canvas.width, canvas.height);
const cx = (rect.x * 2 + rect.width) / 2;
const cy = (rect.y * 2 + rect.height) / 2;
context.translate(cx, cy);
context.rotate(rect.angle);
context.translate(-cx, -cy);
context.fillRect(rect.x, rect.y, rect.width, rect.height);
}
</script>
</body>
</html>
It works fine if the shape isn't rotated, but it breaks down if I try to resize a rotated shape.
For example, If I rotate the rectangle by pressing the key "a" or "s" and then resize it using any of the arrow keys, the rectangle will "drift away". What I'm trying to do is to keep the rectangle still while resizing it, as it happens when it isn't rotated.
Also, I'm trying to find a solution that doesn't involve changing draw(), since I can't do that in the codebase I'm trying to fix this problem.
I'd really appreciate some help.
This is not fixable outside of draw(). The problem is that the draw method always assumes the center of the rectangle is the rotation point, but what you want is to be able to shift the point of rotation based on which direction the rectangle is growing in. The only way to avoid drift WITHOUT changing draw() is to always keep the rectangle centered at the same point. See the commented portions of the code snippet.
The reason you can't fix it outside of draw() is because of the transform reset done on the first line. Otherwise, you'd be able to adjust the transform before and after draw() to accommodate.
const canvas = document.getElementById("canvas");
const context = canvas.getContext("2d");
const rect = {
x: 100,
y: 100,
width: 50,
height: 50,
angle: 0
};
window.onkeydown = keyDown;
draw();
function keyDown(evt) {
if (evt.key == "ArrowRight") {
//rect.x -= 2.5;
rect.width += 5;
}
if (evt.key == "ArrowLeft") {
rect.x -= 5; //2.5;
rect.width += 5;
}
if (evt.key == "ArrowUp") {
//rect.y -= 2.5;
rect.height += 5;
}
if (evt.key == "ArrowDown") {
rect.y -= 5; //2.5;
rect.height += 5;
}
if (evt.key == "a") {
rect.angle -= (45 * Math.PI) / 180;
}
if (evt.key == "s") {
rect.angle += (45 * Math.PI) / 180;
}
draw();
}
function draw() {
// The next line is why you can't fix the drift outside of draw().
context.setTransform(1, 0, 0, 1, 0, 0);
context.clearRect(0, 0, canvas.width, canvas.height);
const cx = (rect.x * 2 + rect.width) / 2;
const cy = (rect.y * 2 + rect.height) / 2;
context.translate(cx, cy);
context.rotate(rect.angle);
context.translate(-cx, -cy);
context.fillStyle = "#000";
context.fillRect(rect.x, rect.y, rect.width, rect.height);
context.fillStyle = "#F00";
context.fillRect(cx, cy, 2, 2);
}
<!DOCTYPE html>
<html>
<body style="margin: 0">
<canvas
id="canvas"
width="400"
height="400"
style="border: 1px solid #d3d3d3"
></canvas>
<script>
</script>
</body>
</html>
Here's another snippet with a solution that requires changes inside of draw(). The idea is that you define cx and cy first and keep them fixed.
const canvas = document.getElementById("canvas");
const context = canvas.getContext("2d");
const rect = {
x: 100,
y: 100,
width: 50,
height: 50,
angle: 0
};
rect.cx = rect.x + rect.width / 2;
rect.cy = rect.y + rect.height / 2;
window.onkeydown = keyDown;
draw();
function keyDown(evt) {
if (evt.key == "ArrowRight") {
rect.width += 5;
}
if (evt.key == "ArrowLeft") {
rect.x -= 5;
rect.width += 5;
}
if (evt.key == "ArrowUp") {
rect.y -= 5;
rect.height += 5;
}
if (evt.key == "ArrowDown") {
rect.height += 5;
}
if (evt.key == "a") {
rect.angle -= (45 * Math.PI) / 180;
}
if (evt.key == "s") {
rect.angle += (45 * Math.PI) / 180;
}
draw();
}
function draw() {
context.setTransform(1, 0, 0, 1, 0, 0);
context.clearRect(0, 0, canvas.width, canvas.height);
context.translate(rect.cx, rect.cy);
context.rotate(rect.angle);
context.translate(-rect.cx, -rect.cy);
context.fillStyle = "#000";
context.fillRect(rect.x, rect.y, rect.width, rect.height);
context.fillStyle = "#F00";
context.fillRect(rect.cx, rect.cy, 2, 2);
}
<!DOCTYPE html>
<html>
<body style="margin: 0">
<canvas
id="canvas"
width="400"
height="400"
style="border: 1px solid #d3d3d3"
></canvas>
<script>
</script>
</body>
</html>
Currently attempting to make a physics simulation for elastic collisions of circles. I am having an issue where I do not know how to run the simulation with two circles interacting at the same time. I am not yet looking to create the interaction between the circles just to have them both running simultaneously. Any help is much appreciated. This is my first post so I apologize if I formatted something incorrectly.
var width = 400;
var height = 400;
var canvas = ctx = false;
var frameRate = 1 / 60; // Seconds
var frameDelay = frameRate * 1000; // ms
var loopTimer = false;
var ball = {
position: {
x: width / 2,
y: height / 2
},
velocity: {
x: 0,
y: 0
},
radius: 15, // 1px = 1cm
restitution: -1
};
var mouse = {
x: 0,
y: 0,
isDown: false
};
function getMousePosition(event) {
mouse.x = event.pageX - canvas.offsetLeft;
mouse.y = event.pageY - canvas.offsetTop;
}
var mouseDown = function(event) {
if (event.which == 1) {
getMousePosition(event);
mouse.isDown = true;
ball.position.x = mouse.x;
ball.position.y = mouse.y;
}
}
var mouseUp = function(event) {
if (event.which == 1) {
mouse.isDown = false;
ball.velocity.y = (ball.position.y - mouse.y) / 10;
ball.velocity.x = (ball.position.x - mouse.x) / 10;
}
}
var setup = function() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
canvas.onmousemove = getMousePosition;
canvas.onmousedown = mouseDown;
canvas.onmouseup = mouseUp;
ctx.fillStyle = 'blue';
ctx.strokeStyle = '#000000';
loopTimer = setInterval(loop, frameDelay);
}
var loop = function() {
if (!mouse.isDown) {
ball.position.x += ball.velocity.x * frameRate * 100;
ball.position.y += ball.velocity.y * frameRate * 100;
}
if (ball.position.y > height - ball.radius) {
ball.velocity.y *= ball.restitution;
ball.position.y = height - ball.radius;
}
if (ball.position.x > width - ball.radius) {
ball.velocity.x *= ball.restitution;
ball.position.x = width - ball.radius;
}
if (ball.position.x < ball.radius) {
ball.velocity.x *= ball.restitution;
ball.position.x = ball.radius;
}
if (ball.position.y < ball.radius) {
ball.velocity.y *= ball.restitution;
ball.position.y = ball.radius;
}
ctx.clearRect(0, 0, width, height);
ctx.save();
ctx.translate(ball.position.x, ball.position.y);
ctx.beginPath();
ctx.arc(0, 0, ball.radius, 0, Math.PI * 2, true);
ctx.fill();
ctx.closePath();
ctx.restore();
if (mouse.isDown) {
ctx.beginPath();
ctx.moveTo(ball.position.x, ball.position.y);
ctx.lineTo(mouse.x, mouse.y);
ctx.stroke();
ctx.closePath();
}
}
setup();
#canvas {
border: solid 1px #ccc;
}
<canvas id="canvas"></canvas>
Here is how I would do it:
Instead of making the ball a kind of static object I made a constructor function (More about that here).
Then I made a ball array to store all the balls.
To make the dragging possible I store a seperate ball, which is not being moved by "physics" in the newBall variable. This ball is either invisible or is the ball currently being dragged.
In mouseDown() the newBall gets positioned under the cursor.
In mouseUp() it gets it's velocity and gets added to the array of animated balls. Also a new newBall gets created.
In loop() I loop two times through the array of animated balls. Once for the physics, once for the painting.
(Normally you would use two different methods with different tickRates to make animation more smooth, because physics calculation doesn't need to happen 60 times per second.
var width = 400;
var height = 400;
var canvas = ctx = false;
var frameRate = 1 / 60; // Seconds
var frameDelay = frameRate * 1000; // ms
var loopTimer = false;
function ball() {
this.position = {
x: width / 2,
y: height / 2
};
this.velocity = {
x: 0,
y: 0
};
this.radius = 15; // 1px = 1cm
this.restitution = -1
};
var balls = [];
var newBall = new ball();
var mouse = {
x: 0,
y: 0,
isDown: false
};
function getMousePosition(event) {
mouse.x = event.pageX - canvas.offsetLeft;
mouse.y = event.pageY - canvas.offsetTop;
}
var mouseDown = function(event) {
if (event.which == 1) {
getMousePosition(event);
mouse.isDown = true;
newBall.position.x = mouse.x;
newBall.position.y = mouse.y;
}
}
var mouseUp = function(event) {
if (event.which == 1) {
mouse.isDown = false;
newBall.velocity.y = (newBall.position.y - mouse.y) / 10;
newBall.velocity.x = (newBall.position.x - mouse.x) / 10;
balls.push(newBall);
newBall = new ball();
}
}
var setup = function() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
canvas.onmousemove = getMousePosition;
canvas.onmousedown = mouseDown;
canvas.onmouseup = mouseUp;
ctx.fillStyle = 'blue';
ctx.strokeStyle = '#000000';
loopTimer = setInterval(loop, frameDelay);
}
var loop = function() {
for (var ball of balls) {
ball.position.x += ball.velocity.x * frameRate * 100;
ball.position.y += ball.velocity.y * frameRate * 100;
if (ball.position.y > height - ball.radius) {
ball.velocity.y *= ball.restitution;
ball.position.y = height - ball.radius;
}
if (ball.position.x > width - ball.radius) {
ball.velocity.x *= ball.restitution;
ball.position.x = width - ball.radius;
}
if (ball.position.x < ball.radius) {
ball.velocity.x *= ball.restitution;
ball.position.x = ball.radius;
}
if (ball.position.y < ball.radius) {
ball.velocity.y *= ball.restitution;
ball.position.y = ball.radius;
}
}
ctx.clearRect(0, 0, width, height);
for (var ball of balls) {
ctx.save();
ctx.translate(ball.position.x, ball.position.y);
ctx.beginPath();
ctx.arc(0, 0, ball.radius, 0, Math.PI * 2, true);
ctx.fill();
ctx.closePath();
ctx.restore();
}
ctx.save();
ctx.translate(newBall.position.x, newBall.position.y);
ctx.beginPath();
ctx.arc(0, 0, newBall.radius, 0, Math.PI * 2, true);
ctx.fill();
ctx.closePath();
ctx.restore();
if (mouse.isDown) {
ctx.beginPath();
ctx.moveTo(newBall.position.x, newBall.position.y);
ctx.lineTo(mouse.x, mouse.y);
ctx.stroke();
ctx.closePath();
}
}
setup();
#canvas {
border: solid 1px #ccc;
}
<canvas id="canvas"></canvas>
Now to get a bit more complex:
I added tickDelay and tickTimer to use them in a tickLoop
The ball constructor now has two methods:
show() draws the ball on the canvas
tick() does the pysics stuff (dt= deltaTime: time since last tick)
newBall is now null if the mouse isn't pressed
setup() initializes the width and height according to the <canvas> elements real size
tick() loops through the balls and calls .tick() tickDelay is in milliseconds so it gets divided by 1000
drawFrame() is your former loop() and does the drawing stuff
var width = 400;
var height = 400;
var canvas = ctx = false;
var frameRate = 1 / 60; // Seconds
var frameDelay = frameRate * 1000; // ms
var tickDelay = frameDelay * 2; //ticks 2 times slower than frames
var frameTimer;
var tickTimer;
function ball() {
this.position = {
x: width / 2,
y: height / 2
};
this.velocity = {
x: 0,
y: 0
};
this.radius = 15; // 1px = 1cm
this.restitution = -.99;
this.show = function() {
ctx.save();
ctx.translate(this.position.x, this.position.y);
ctx.beginPath();
ctx.arc(0, 0, this.radius, 0, Math.PI * 2, true);
ctx.fill();
ctx.closePath();
ctx.restore();
};
this.tick = function(dt) {
this.position.x += this.velocity.x * dt;
this.position.y += this.velocity.y * dt;
if (this.position.y > height - this.radius) {
this.velocity.y *= this.restitution;
this.position.y = height - this.radius;
}
if (this.position.x > width - this.radius) {
this.velocity.x *= this.restitution;
this.position.x = width - this.radius;
}
if (this.position.x < this.radius) {
this.velocity.x *= this.restitution;
this.position.x = this.radius;
}
if (this.position.y < this.radius) {
this.velocity.y *= this.restitution;
this.position.y = this.radius;
}
}
};
var balls = [];
var newBall;
var mouse = {
x: 0,
y: 0,
isDown: false
};
function getMousePosition(event) {
mouse.x = event.pageX - canvas.offsetLeft;
mouse.y = event.pageY - canvas.offsetTop;
}
function mouseDown(event) {
if (event.which == 1) {
getMousePosition(event);
mouse.isDown = true;
if (!newBall) newBall = new ball();
newBall.position.x = mouse.x;
newBall.position.y = mouse.y;
}
}
function mouseUp(event) {
if (event.which == 1) {
mouse.isDown = false;
newBall.velocity.y = (newBall.position.y - mouse.y);
newBall.velocity.x = (newBall.position.x - mouse.x);
balls.push(newBall);
newBall = null;
}
}
function setup() {
canvas = document.getElementById("canvas");
width = canvas.getBoundingClientRect().width;
height = canvas.getBoundingClientRect().height;
ctx = canvas.getContext("2d");
canvas.onmousemove = getMousePosition;
canvas.onmousedown = mouseDown;
canvas.onmouseup = mouseUp;
ctx.fillStyle = 'blue';
ctx.strokeStyle = '#000000';
requestAnimationFrame(drawFrame);
frameTimer = setInterval(drawFrame, frameDelay);
tickTimer = setInterval(tick, tickDelay);
}
function tick() {
for (var ball of balls) ball.tick(tickDelay * .001);
}
function drawFrame() {
ctx.clearRect(0, 0, width, height);
for (var ball of balls) ball.show();
if (newBall) newBall.show(ctx);
if (mouse.isDown && newBall) {
ctx.beginPath();
ctx.moveTo(newBall.position.x, newBall.position.y);
ctx.lineTo(mouse.x, mouse.y);
ctx.stroke();
ctx.closePath();
}
}
setup();
#canvas {
border: solid 1px #ccc;
}
<canvas id="canvas"></canvas>
A really simple way would to do exactly the same as you do now, but not initiate all functions as a variable. Change all the variables that are functions to just functions, and where you call them. At least the variable called ball. Then after that you could make two variables like this
ball1 = new ball();
ball2 = new ball();
Your script is kind of messy so hard for me to say if this will go through without any errors, but if it does, I am more than happy to help. This is not the very best solution if you only go for the way i presented now so please do not use this as you solution, but more as a way to get started. Also you will not really learn anything of it if we just gave you the answer
Edit:
Another thing to mark is that using setInterval for games and graphical projects may be a bad idea since JavaScript is single threaded. A better solution is using requestAnimationFrame()
It would look something like this
function mainLoop() {
update();
draw();
requestAnimationFrame(mainLoop);
}
// Start things off
requestAnimationFrame(mainLoop);
How do I shoot bullets from my Player X and Y towards the mouse x and y?
I can find the angle of the mouse X and Y but I have no idea how to create a bullet which will fly towards the mouse.
The code for the mouse coordinates are (dx, dy).
Also, if you could explain the logic behind what you did and how you did it, I would be greatful.
Thanks!
Fiddle
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var pressingDown = false;
var pressingUp = false;
var pressingLeft = false;
var pressingRight = false;
var mouseX, mouseY;
function Player(x, y) {
this.x = x;
this.y = y;
this.angle;
}
Player.prototype.draw = function() {
context.save();
context.translate(this.x, this.y);
context.rotate(this.angle);
context.beginPath();
context.fillStyle = "green";
context.arc(0, 0, 30, 0, 2 * Math.PI);
context.fill();
context.fillStyle = "red";
context.fillRect(0, -10, 50, 20);
context.restore();
}
Player.prototype.update = function(mouseX, mouseY) {
var dx = mouseX - this.x;
var dy = mouseY - this.y;
this.angle = Math.atan2(dy, dx);
}
canvas.addEventListener('mousemove', mouseMove);
function mouseMove(evt) {
mouseX = evt.x;
mouseY = evt.y;
}
var player = new Player(350, 250);
function updatePlayer() {
context.clearRect(0, 0, canvas.width, canvas.height);
player.draw();
player.update(mouseX, mouseY);
updatePlayerPosition();
}
document.onkeydown = function(event) {
if (event.keyCode === 83) //s
pressingDown = true;
else if (event.keyCode === 87) //w
pressingUp = true;
else if (event.keyCode === 65) //a
pressingLeft = true;
else if (event.keyCode === 68) //d
pressingRight = true;
}
document.onkeyup = function(event) {
if (event.keyCode === 83) //s
pressingDown = false;
else if (event.keyCode === 87) //w
pressingUp = false;
else if (event.keyCode === 65) //a
pressingLeft = false;
else if (event.keyCode === 68) //d
pressingRight = false;
}
updatePlayerPosition = function() {
if (pressingRight)
player.x += 1;
if (pressingLeft)
player.x -= 1;
if (pressingDown)
player.y += 1;
if (pressingUp)
player.y -= 1;
}
function update() {
updatePlayer();
}
setInterval(update, 0)
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
body {
background-color: black;
}
canvas {
position: absolute;
margin: auto;
left: 0;
right: 0;
border: solid 1px white;
border-radius: 10px;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="application/javascript">
(function() {
"use strict";
var canvasWidth = 180;
var canvasHeight = 160;
var canvas = null;
var bounds = null;
var ctx = null;
var mouseX = 0.0;
var mouseY = 0.0;
var player = {
x: (canvasWidth * 0.5) | 0,
y: (canvasHeight * 0.5) | 0,
dx: 0.0,
dy: 0.0,
angle: 0.0,
radius: 17.5,
tick: function() {
this.angle = Math.atan2(mouseY - this.y,mouseX - this.x);
},
render: function() {
ctx.fillStyle = "darkred";
ctx.strokeStyle = "black";
ctx.translate(this.x,this.y);
ctx.rotate(this.angle);
ctx.beginPath();
ctx.moveTo(this.radius,0.0);
ctx.lineTo(-0.5 * this.radius,0.5 * this.radius);
ctx.lineTo(-0.5 * this.radius,-0.5 * this.radius);
ctx.lineTo(this.radius,0.0);
ctx.fill();
ctx.stroke();
ctx.rotate(-this.angle);
ctx.translate(-this.x,-this.y);
}
};
var bullet = {
x: (canvasWidth * 0.5) | 0,
y: (canvasHeight * 0.5) | 0,
dx: 0.0,
dy: 0.0,
radius: 5.0,
tick: function() {
this.x += this.dx;
this.y += this.dy;
if (this.x + this.radius < 0.0
|| this.x - this.radius > canvasWidth
|| this.y + this.radius < 0.0
|| this.y - this.radius > canvasHeight)
{
this.dx = 0.0;
this.dy = 0.0;
}
},
render: function() {
ctx.fillStyle = "darkcyan";
ctx.strokeStyle = "white";
ctx.beginPath();
ctx.arc(this.x,this.y,this.radius,0.0,2.0*Math.PI,false);
ctx.fill();
ctx.stroke();
}
};
function loop() {
// Tick
bullet.tick();
player.tick();
// Render
ctx.fillStyle = "gray";
ctx.fillRect(0,0,canvasWidth,canvasHeight);
bullet.render();
player.render();
//
requestAnimationFrame(loop);
}
window.onmousedown = function(e) {
// The mouse pos - the player pos gives a vector
// that points from the player toward the mouse
var x = mouseX - player.x;
var y = mouseY - player.y;
// Using pythagoras' theorm to find the distance (the length of the vector)
var l = Math.sqrt(x * x + y * y);
// Dividing by the distance gives a normalized vector whose length is 1
x = x / l;
y = y / l;
// Reset bullet position
bullet.x = player.x;
bullet.y = player.y;
// Get the bullet to travel towards the mouse pos with a new speed of 10.0 (you can change this)
bullet.dx = x * 10.0;
bullet.dy = y * 10.0;
}
window.onmousemove = function(e) {
mouseX = e.clientX - bounds.left;
mouseY = e.clientY - bounds.top;
}
window.onload = function() {
canvas = document.getElementById("canvas");
canvas.width = canvasWidth;
canvas.height = canvasHeight;
bounds = canvas.getBoundingClientRect();
ctx = canvas.getContext("2d");
loop();
}
})();
</script>
</body>
</html>
Moving from point to point.
Given two points p1 and p2, each point as a coordinate (x,y) and a speed value that is the number of pixels per step, there are two methods you can use to move between them.
Cartesian
Calculate the vector from p1 to p2
var vx = p2.x - p1.x;
var vy = p2.y - p1.y;
Then calculate the delta by getting the length of the vector, normalise it (make the vector 1 pixel long) then multiply by the speed
var dist = Math.sqrt(vx * vx + vy * vy);
var dx = vx / dist;
var dy = vy / dist;
dx *= speed;
dy *= speed;
This can be optimized a little by scaling the speed with the distance.
var scale = speed / Math.sqrt(vx * vx + vy * vy);
var dx = vx / dist;
var dy = vy / dist;
Polar
The other way is to get the direction from p1 to p2 and use that create the deltas
var dir = Math.atan2(p2.y - p1.y, p2.x - p1.x);
var dx = Math.cos(dir) * speed;
var dx = Math.sin(dir) * speed;
Animate
Once you have the delta you just need to update the position via addition.
const bullet = {x : p1.x, y : p1.y}; // set the bullet start pos
// then each frame add the delta
bullet.x += dx;
bullet.y += dy;
// draw the bullet
I'm trying to get this car to move with the arrow keys and rotate as well. The car loaded onto the canvas, but its not moving with the keys. I think I've put in everything I need, or I'm wrong. Or, there just some minor mistakes. Anyways, please help a noob like me :D!
<!doctype html>
<html lang="en">
<head>
<title>Ball</title>
<script src="http://code.jquery.com/jquery-git2.js"></script>
</head>
<body>
<center>
<canvas id="gameCanvas" width="500" height="500" style="border:5px solid green"></canvas>
<script src="js/Game.js"></script>
</center>
</body>
</html>
JS:
//Set context for canvas
var context = $('#gameCanvas')[0].getContext('2d');
//Dimensions For Canvas
var width = $('#gameCanvas').width();
var height = $('#gameCanvas').height();
//Image for Car
var car = new Image();
car.src = "http://thumb1.shutterstock.com/thumb_small/338038/192139124/stock-vector-illustration-of-a-red-sports-car-top-view-192139124.jpg";
//Car Variables and position
var x = 80;
var y = 80;
var vx = 0;
var vy = 0;
var angle = 0;
var mod = 0;
//Draws car during motion
var moveInterval = setInterval(function () {
draw();
}, 30);
//Clears Canvas
function draw()
{
context.clearRect(0, 0, gameCanvas.width, gameCanvas.height);
// Change direction and velocity of car
x += (vx * mod) * Math.cos(Math.PI / 180 * angle);
y += (vy * mod) * Math.sin(Math.PI / 180 * angle);
context.save();
context.translate(x, y);
context.rotate(Math.PI / 180 * angle);
context.drawImage(car, -(car.width / 2), -(car.height / 2));
context.restore();
}
//Codes for keyboard keys
$('#gameCanvas').keydown(function(event) {
code = event.keyCode;
if (code == 37) vx = -10.0; // left key pressed
if (code == 39) vx = 10.0; // rightkey pressed
if (code == 38) vy = -2.0; // up key pressed
if (code == 40) vy = 2.0; // down key pressed
});
$('#gameCanvas').up(function(event) {
code = event.keyCode;
if (code == 37) vx = 0.0; // leftkey not pressed
if (code == 39) vx = 0.0; // rightkey not pressed
if (code == 38) vy = 0.0; // upkey not pressed
if (code == 40) vy = 0.0; // downkey not pressed
});
update();
Maybe something like this:
//Set context for canvas
var context = $('#gameCanvas')[0].getContext('2d');
//Dimensions For Canvas
var width = $('#gameCanvas').width();
var height = $('#gameCanvas').height();
//Image for Car
var car = new Image();
car.src = "http://thumb1.shutterstock.com/thumb_small/338038/192139124/stock-vector-illustration-of-a-red-sports-car-top-view-192139124.jpg";
//Car Variables and position
var x = 80;
var y = 80;
var vx = 0;
var vy = 0;
var angle = 0;
var mod = 0;
draw();
function draw()
{
context.clearRect(0, 0, gameCanvas.width, gameCanvas.height);
x += (vx * mod) * Math.cos(Math.PI / 180 * angle);
y += (vy * mod) * Math.sin(Math.PI / 180 * angle);
console.log(vx);
console.log(vy);
context.translate(vx, vy);
context.rotate(Math.PI / 180 * angle);
context.drawImage(car, x, y);
}
$(document).keydown(function(event) {
code = event.keyCode;
if (code == 37) { vx = -10.0; } // left key pressed
if (code == 39){ vx = 10.0;} // rightkey pressed
if (code == 38){ vy = -2.0;} // up key pressed
if (code == 40){ vy = 2.0; } // down key pressed
draw();
});
So first, I uploaded a car to the canvas and gave it turning and motion properties. I tried to draw a circle to go alongside the car but it is not working properly. The circle is alone and flickering for some reason. I removed the timeout completely, and both the circle and car disappeared. Adjusting the timeout rate doesn't remove the flicker. Help me get them on the screen and keep them there together please?
http://jsbin.com/zogeraduze/1/edit?html,js,output
I don't have your car image, but it seems like you have a setInterval set to 30ms and you call a timeout every 10ms (which is equivalent to a setInterval), each time clearing the canvas, hence creating a flickering. You should have only one repaint function that should clear the canvas, draw the car and then draw the circle.
try
//Setting the canvas and context
var canvas = document.getElementById('gameCanvas');
var context = canvas.getContext('2d');
//Uploading car
var car = new Image();
car.src = "file:///H:/Desktop/Game/img/car.png";
//Setting properties of car
var x = 450;
var y = 730;
var speed = 10;
var angle = 990;
var mod = 0;
//Event listeners for keys
window.addEventListener("keydown", keypress_handler, false);
window.addEventListener("keyup", keyup_handler, false);
//Drawing the car turning and changing speed
function draw() {
x += (speed * mod) * Math.cos(Math.PI / 180 * angle);
y += (speed * mod) * Math.sin(Math.PI / 180 * angle);
context.save();
context.translate(x, y);
context.rotate(Math.PI / 180 * angle);
context.drawImage(car, -(car.width / 2), -(car.height / 2));
context.restore();
}
//Setting the keys
function keyup_handler(event) {
console.log('a');
if (event.keyCode == 38 || event.keyCode == 40) {
mod = 0;
}
}
//Setting all of the keys
function keypress_handler(event) {
console.log(event.keyCode);
if (event.keyCode == 38) {
mod = 1;
}
if (event.keyCode == 40) {
mod = -1;
}
if (event.keyCode == 37) {
angle -= 5;
}
if (event.keyCode == 39) {
angle += 5;
}
}
var context = $('#gameCanvas')[0].getContext('2d');
var width = $('#gameCanvas').width();
var height = $('#gameCanvas').height();
var circleX = width / 2;
var circleY = height / 2;
var circleVX = 1.0;
var circleVY = 0.0;
var circleR = 30;
function update() {
context.clearRect(0, 0, width, height);
/*
circleX = Math.random() * (width - 2 * circleR) + circleR;
circleY = Math.random() * (height - 2 * circleR) + circleR;
*/
draw();
drawCircle(circleX, circleY, circleR);
setTimeout(update, 10);
}
function canvasClick(event) {
var clickX = event.pageX;
var clickY = event.pageY;
var edgeX = clickX - circleX;
var edgeY = clickY - circleY;
var r = Math.sqrt(edgeX * edgeX + edgeY * edgeY);
if (r < circleR) {
context.clearRect(0, 0, width, height);
}
}
function drawCircle(x, y, r) {
context.beginPath();
context.arc(x, y, r, 0, 2 * Math.PI, false);
context.fillStyle = 'red';
context.fill();
context.lineWidth = 3;
context.strokeStyle = 'black';
context.stroke();
}
$('#gameCanvas').click(canvasClick);
update();
Also, look into https://developer.mozilla.org/en-US/docs/Web/API/window.requestAnimationFrame instead of using timeouts