How can I get my JS car to move? - javascript

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();
});

Related

Detecting edge of canvas and allowing for movement away from it

I have a small game where the player is moving a circle within a canvas. I am having issues with detecting the edges of the canvas, disallowing a player to move past those edges, and allowing the user to navigate away from any given edge.
Currently, the player can hit canvas edges and move away successfully, most of the time. However, with a combination of certain movements and collision along an edge, the player will become "stuck".
How can I go about creating simple canvas edge collision detection and allow the user to move freely after the event?
My code:
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x = canvas.width / 2;
var y = canvas.height - 30;
var dx = 2;
var dy = -2;
var ballRadius = 10;
var rightPressed = false;
var leftPressed = false;
var upPressed = false;
var downPressed = false;
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
function keyDownHandler(e) {
if (e.keyCode == 65) {
rightPressed = true;
}
if (e.keyCode == 68) {
leftPressed = true;
}
if (e.keyCode == 87) {
upPressed = true;
}
if (e.keyCode == 83) {
downPressed = true;
}
}
function keyUpHandler(e) {
if (e.keyCode == 65) {
rightPressed = false;
}
if (e.keyCode == 68) {
leftPressed = false;
}
if (e.keyCode == 87) {
upPressed = false;
}
if (e.keyCode == 83) {
downPressed = false;
}
}
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI * 2);
ctx.strokeStyle = "black";
ctx.stroke();
ctx.closePath();
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();
if (x + dx > canvas.width - ballRadius || x + dx < ballRadius - 3) {
dx = -dx;
}
if (y + dy > canvas.height - ballRadius || y + dy < ballRadius - 3) {
dy = -dy;
}
if (rightPressed) {
x -= dx;
}
if (leftPressed) {
x += dx;
}
if (upPressed) {
y += dy;
}
if (downPressed) {
y -= dy;
}
}
setInterval(draw, 10);
<canvas id="myCanvas"></canvas>
Well i have to admit that have been long time since i don't touch older libraries stored in the bault. Luckley i got the sources at hand, so after taking a look i will tell a method that works for me regarding how to detect the colision of a ball object against a wall.
I guess it will fit to you needs, don't know if the better or worse solution, but works!. Let start by defining how we represent the data for each ball, recall our friends of unix that says that part of the complexity is in the data structure as it is part of the algorithm as a whole... but enought chat, going to the matters.. by using this kind of data structure for representing a Ball
class Ball
{
radio : number
x : number
y : number
}
So you can draw the ball this way:
function draw (Graphics g)
{
int r = ball.getRadio ();
int diam = rad * 2;
int px = (int) ball.getPx () - r;
int py = (int) ball.getPy () - r;
g.setColor (niceColor);
g.fillArc (px,py,diameter,diameter,0,360); // Fills a circular or elliptical arc covering the specified rectangle
}
// Disclaimer, i don't know well the primitives for graphical routines in canvas, but i would assume that you will have somethign to draw a circle with all of that. You got px, py, x, y, radio, diameter.
Anyway the answer for the question comes here where you can use this code:
function isAHorizontalCollision (ball c,int width)
{
return (c.x > width - c.radio || c.x < radio);
}
function isAVerticalCollision (ball c,int height)
{
return (c.y > height - c.radio || c.y < radio);
}
// Assume that enclosing rectangle where the ball can move is between (0,width) for horizontal, and (top,0) vertical.
Is important to advise that this work only if the x values goes incrementally from left to right and the y goes decrementally from top to bottom.
Hope my typescript alike code fits well for explaining. I have a lot of source files in java for this. If need more. (For example collision between two circles).
If you have time i would recommend to check this out, very very powerfull stuff in there.
You complicated things a bit with all the Boolean variables...
The same can be done with just a the dx and dy those are your speed set them to 0 to stop.
Also it look like you where inverting the direction of the keys that was the lines:
if (x + dx > canvas.width - ballRadius || x + dx < ballRadius - 3) {
dx = -dx;
}
if (y + dy > canvas.height - ballRadius || y + dy < ballRadius - 3) {
dy = -dy;
}
When those condition are true the up is now down and the right is left, not sure if that was your intended behavior, when it worked it looked like the ball was bouncing from the edge but from that point on the key was inverted... I remove that from my fix.
Here is my approach, I added a bit of math fun to animate your player:
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var x = canvas.width / 2;
var y = canvas.height / 2;
var dx = 0;
var dy = 0;
var ballRadius = 10;
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
function keyDownHandler(e) {
if (e.keyCode == 65) dx = -2
if (e.keyCode == 68) dx = 2
if (e.keyCode == 87) dy = -2
if (e.keyCode == 83) dy = 2
}
function keyUpHandler(e) {
if (e.keyCode == 65) dx = 0
if (e.keyCode == 68) dx = 0
if (e.keyCode == 87) dy = 0
if (e.keyCode == 83) dy = 0
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();
var fx = x + dx
var fy = y + dy
if (ballRadius < fx && fx < canvas.width - ballRadius) x = fx;
if (ballRadius < fy && fy < canvas.height - ballRadius) y = fy;
}
setInterval(draw, 10);
var hr = ballRadius / 2 - 1
var pi2 = Math.PI * 2
var i = 0
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, pi2);
ctx.strokeStyle = "black";
ctx.stroke();
// draw some small moving circles inside
ctx.beginPath();
ctx.fillStyle = "red";
ctx.arc(x + hr * Math.sin(i), y + hr * Math.cos(i), hr, 0, pi2);
ctx.fill();
ctx.beginPath();
ctx.fillStyle = "blue";
ctx.arc(x - hr * Math.sin(i), y - hr * Math.cos(i), hr, 0, pi2);
ctx.fill();
ctx.closePath();
i += 0.1 + Math.abs(dx)/15 + Math.abs(dy)/15
}
<canvas id="myCanvas" style="border:1px solid #000000;"></canvas>
Thanks for the help from the two of you who answered my question. Because of you two, I was able to successfully find a solution.
Originally, I was using this to determine the edges of the canvas, and adjust direction accordingly:
if (x + dx > canvas.width - ballRadius || x + dx < ballRadius - 3) {
dx = -dx;
}
if (y + dy > canvas.height - ballRadius || y + dy < ballRadius - 3) {
dy = -dy;
}
However, as pointed out, that reverses the movement direction, making it basically useless for my intended purpose. Not only that, but all 4 sides of the canvas act in a slightly different manor from each other.
Using the feedback from the other answer, here's the solution I am using now, which works wonderfully:
if (x + dx > canvas.width - ballRadius) {
var fx = x - dx;
x = fx;
}
if (x + dx < ballRadius) {
var fx = x + dx;
x = fx;
}
if (y + dy > canvas.height - ballRadius) {
var fy = y + dy;
y = fy;
}
if (y + dy < ballRadius) {
var fy = y - dy;
y = fy;
}
This way, I am detecting all 4 sides successfully, stopping user motion on contact, and allowing the player to move away from the side of the canvas.

Shooting bullets from player towards mouse?

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

rotate the camera horizontally and vertically three.js

I have the following code that makes my camera rotate vertically when i press a key (this works great):
var cameraOrginX = 0, cameraOrginY = 0, cameraOrginZ = 0;
var cameraEndX = 0, cameraEndY = -707, cameraEndZ = 707;
var angle = 1;
function onDocumentKeyDown(event){
var keyCode = event.which;
console.log(keyCode);
if(keyCode == 87 || keyCode == 83){
if (keyCode == 87) {
angle = 1;
console.log("forward " + angle);
}
else if (keyCode == 83) {
angle = -1;
console.log("backward " + angle);
}
}
if(keyCode == 68 || keyCode == 65){
if (keyCode == 68) {
angle = 1;
console.log("right " + angle);
}
else if (keyCode == 65) {
angle = -1;
console.log("left " + angle);
}
}
//rotate vertically
var radiansVert = angle * Math.PI / 180.0;
var radiansHori = angle * Math.PI / 180.0;
var cosTheta = Math.cos(radiansVert);
var sinTheta = Math.sin(radiansVert);
var aVert = cosTheta * (cameraEndY-cameraOrginY);
var bVert = sinTheta * (cameraEndZ-cameraOrginZ);
var cVert = sinTheta * (cameraEndY-cameraOrginY);
var dVert = cosTheta * (cameraEndZ-cameraOrginZ);
cameraEndY = aVert - bVert + cameraOrginY;
cameraEndZ = cVert + dVert + cameraOrginZ;
camera.position.x = cameraOrginX + cameraEndX;
camera.position.y = cameraOrginY + cameraEndY;
camera.position.z = cameraOrginZ + cameraEndZ;
//
}
But now i want to make my camera also rotate horizontally... i tried copy and pasting the code between the comments and changing the variable names so it would work on the x and y axis but that gave me some weird results what i was not really looking for ;) could someone give me a tip or point me in the right direction on how to do this? i am still learning and any help would be greatly appriciated :)
if there is more code needed to make my problem clear let me know i can also make a jsfiddle if you want!

Drawing circle and keeping the first uploaded sprite

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

Simple HTML and JS code won't work?

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>

Categories