Changing my Jquery project to plain javascript - javascript

I created a breakout game for a school project using jquery and a helpful online tutorial.
The working fiddle is here: http://jsfiddle.net/Kinetic915/kURvf/
EDIT revised fiddle: http://jsfiddle.net/Kinetic915/nVctR/
I have changed most to javascript but am having problems changing the jquery code that renders the ball to javascript.
I have Marked and left spaces in the areas where there are problems.
Thank you very much for any help given!!
//***********************************************************************************
// START CODE
//***********************************************************************************
// VARIABLES and other initializing functions are here
function start() {
//******************************************************************************
//JQUERY
// HERE IS THE MAIN PROBLEM!!!!!!
// HERE IS THE MAIN PROBLEM!!!!!!
Cir = $('#canvas')[0].getContext("2d");
//JQUERY
//changing to Cir = canvas.getContext("2d"); causes the code to FAIL.
return setInterval(drawCIRCLE, 10);
}
function windowsize() {
//success with javascript
WIDTH.width = window.innerWidth;
HEIGHT.height = window.innerHeight;
WIDTH = window.innerWidth;
HEIGHT = window.innerHeight;
//Previous JQUERY:
// WIDTH = $("#canvas")[0].width = $(window).width();
// HEIGHT = $("#canvas")[0].height = $(window).height();
}
windowsize();
var x = WIDTH / 2 - 30; //divide by 2 start in middle of window
var y = HEIGHT / 2;
//THIS DRAWS THE CIRCLE
function circle() {
//Cir.clearRect(0, 0, WIDTH, HEIGHT);
Cir.beginPath();
Cir.arc(x, y, 10, 0, Math.PI * 2, true);
Cir.closePath();
Cir.fill();
}
// Initialization of the Block array, rendering of the gutter area and coordinate box
were here
//*********************************************************
// HERE IS THE CODE THAT RENDERS THE BALL MOVEMENT ETC.
//draw a circle
function drawCIRCLE() {
clear();
circle();
drawPADDLE(); //calls draw paddle function
drawGUTTER(); // calls draw gutter function
drawCOORBOX(); // calls draw coordinate box function
drawBRICKS(); //calls the function to draw the boxes
//have we hit a brick?
rowheight = brickheight + padding;
colwidth = brickwidth + padding;
row = Math.floor(y / rowheight);
col = Math.floor(x / colwidth);
//if so, reverse the ball and mark the brick as broken
if (y < numrows * rowheight && row >= 0 && col >= 0 && bricks[row][col] == 1) {
dy = -dy;
bricks[row][col] = 0;
}
if (x + dx > WIDTH || x + dx < 0) dx = -dx;
if (y + dy < 0) dy = -dy;
else if (y + dy > ((HEIGHT - paddleh) - ppoffset) || y + dy > HEIGHT) {
if (x > paddlex && x < paddlex + paddlew)
//switch! once first is true, then second goes
dy = -dy;
else if (y + dy > ((HEIGHT - paddleh) - ppoffset) && y + dy > HEIGHT) {
clearInterval(intervalId);
}
}
x += dx;
y += dy;
if (rightpress) paddlex += 5;
else if (leftpress) paddlex -= 5;
}
function clear() {
Cir.clearRect(0, 0, WIDTH, HEIGHT);
//Is this jquery? I suspect this part of the code making the circle rendering fail.
}
start();
init_paddle();
initbricks();

Ages ago I wrote a similar code in pure JavaScript here
this code uses pure javascript and no library.The code is well commented(I think :))
I generally attached events like this
document.onkeydown = function(e)
{
e = e || window.event;
switch (e.keyCode) { // which key was pressed?
case 32: // release ball.
if(!game.ball.isFree)
{
game.ball.isFree = true;
game.ball.directionX = game.ball.directionY = 1;
game.ball.x = game.ball.offsetLeft;
game.ball.y = game.screen.offsetHeight - game.ball.offsetTop;
}
break;
case 37: // left, rotate player left
game.bar.direction = -1;
break;
case 39: // right, rotate player right
game.bar.direction = 1;
break;
}
}
document.onkeyup = function(e)
{
e = e || window.event;
switch (e.keyCode)
{
case 37:
case 39:
game.bar.direction = 0;
break;
}
}
},
Ofcourse you have many other places which might need porting so a helpful break down of questions would be easier to answer :)
Hope this helps

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.

how to call a javascript function from html?

Is there anything wrong in how i am calling the init2 function in my html file.
It's works fine when i run it in jsfiddle after removing the script reference in head.when i try to run it locally in my machine,there is no output in my browser.
i am not using any onclick methods,i want everything to be loaded when the page is loaded.
jsfiddle:https://jsfiddle.net/sukchguj/2/
This is the code i am trying to run locally.And also both the html and js files are in the same directory.
<!DOCTYPE html>
<html>
<head>
<title>js</title>
<script src="canvas.js"></script>
</head>
<body onload='init2()'>
<canvas id="canvas" width="1000" height="1000">
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>
<!-- This image will be displayed on the canvas -->
<img id="myImage" src="https://image.slidesharecdn.com/bareconf-140329111624-phpapp02/95/draft-scientific-paper-1-638.jpg?cb=1396091812" style = "display: none">
</body>
</html>
canvas.js
// holds all our boxes
var boxes2 = [];
// New, holds the 8 tiny boxes that will be our selection handles
// the selection handles will be in this order:
// 0 1 2
// 3 4
// 5 6 7
var selectionHandles = [];
// Hold canvas information
var canvas;
var ctx;
var WIDTH;
var HEIGHT;
var INTERVAL = 20; // how often, in milliseconds, we check to see if a redraw is needed
var isDrag = false;
var isResizeDrag = false;
var expectResize = -1; // New, will save the # of the selection handle if the mouse is over one.
var mx, my; // mouse coordinates
// when set to true, the canvas will redraw everything
// invalidate() just sets this to false right now
// we want to call invalidate() whenever we make a change
var canvasValid = false;
// The node (if any) being selected.
// If in the future we want to select multiple objects, this will get turned into an array
var mySel = null;
// The selection color and width. Right now we have a red selection with a small width
var mySelColor = '#CC0000';
var mySelWidth = 2;
var mySelBoxColor = 'darkred'; // New for selection boxes
var mySelBoxSize = 6;
// we use a fake canvas to draw individual shapes for selection testing
var ghostcanvas;
var gctx; // fake canvas context
// since we can drag from anywhere in a node
// instead of just its x/y corner, we need to save
// the offset of the mouse when we start dragging.
var offsetx, offsety;
// Padding and border style widths for mouse offsets
var stylePaddingLeft, stylePaddingTop, styleBorderLeft, styleBorderTop;
// Box object to hold data
function Box2() {
this.x = 0;
this.y = 0;
this.w = 1; // default width and height?
this.h = 1;
this.fill = '#444444';
}
// New methods on the Box class
Box2.prototype = {
// we used to have a solo draw function
// but now each box is responsible for its own drawing
// mainDraw() will call this with the normal canvas
// myDown will call this with the ghost canvas with 'black'
draw: function(context, optionalColor) {
if (context === gctx) {
context.fillStyle = 'black'; // always want black for the ghost canvas
} else {
context.fillStyle = this.fill;
}
// We can skip the drawing of elements that have moved off the screen:
if (this.x > WIDTH || this.y > HEIGHT) return;
if (this.x + this.w < 0 || this.y + this.h < 0) return;
context.fillRect(this.x,this.y,this.w,this.h);
// draw selection
// this is a stroke along the box and also 8 new selection handles
if (mySel === this) {
context.strokeStyle = mySelColor;
context.lineWidth = mySelWidth;
context.strokeRect(this.x,this.y,this.w,this.h);
// draw the boxes
var half = mySelBoxSize / 2;
// 0 1 2
// 3 4
// 5 6 7
// top left, middle, right
selectionHandles[0].x = this.x-half;
selectionHandles[0].y = this.y-half;
selectionHandles[1].x = this.x+this.w/2-half;
selectionHandles[1].y = this.y-half;
selectionHandles[2].x = this.x+this.w-half;
selectionHandles[2].y = this.y-half;
//middle left
selectionHandles[3].x = this.x-half;
selectionHandles[3].y = this.y+this.h/2-half;
//middle right
selectionHandles[4].x = this.x+this.w-half;
selectionHandles[4].y = this.y+this.h/2-half;
//bottom left, middle, right
selectionHandles[6].x = this.x+this.w/2-half;
selectionHandles[6].y = this.y+this.h-half;
selectionHandles[5].x = this.x-half;
selectionHandles[5].y = this.y+this.h-half;
selectionHandles[7].x = this.x+this.w-half;
selectionHandles[7].y = this.y+this.h-half;
context.fillStyle = mySelBoxColor;
for (var i = 0; i < 8; i ++) {
var cur = selectionHandles[i];
context.fillRect(cur.x, cur.y, mySelBoxSize, mySelBoxSize);
}
}
} // end draw
}
//Initialize a new Box, add it, and invalidate the canvas
function addRect(x, y, w, h, fill) {
var rect = new Box2;
rect.x = x;
rect.y = y;
rect.w = w
rect.h = h;
rect.fill = fill;
boxes2.push(rect);
invalidate();
}
//***************************
// This will load the image into the variable "im"
var im = document.getElementById("myImage");
//***************************
// initialize our canvas, add a ghost canvas, set draw loop
// then add everything we want to intially exist on the canvas
function init2() {
canvas = document.getElementById('canvas');
HEIGHT = canvas.height;
WIDTH = canvas.width;
ctx = canvas.getContext('2d');
ghostcanvas = document.createElement('canvas');
ghostcanvas.height = HEIGHT;
ghostcanvas.width = WIDTH;
gctx = ghostcanvas.getContext('2d');
//fixes a problem where double clicking causes text to get selected on the canvas
canvas.onselectstart = function () { return false; }
// fixes mouse co-ordinate problems when there's a border or padding
// see getMouse for more detail
if (document.defaultView && document.defaultView.getComputedStyle) {
stylePaddingLeft = parseInt(document.defaultView.getComputedStyle(canvas, null)['paddingLeft'], 10) || 0;
stylePaddingTop = parseInt(document.defaultView.getComputedStyle(canvas, null)['paddingTop'], 10) || 0;
styleBorderLeft = parseInt(document.defaultView.getComputedStyle(canvas, null)['borderLeftWidth'], 10) || 0;
styleBorderTop = parseInt(document.defaultView.getComputedStyle(canvas, null)['borderTopWidth'], 10) || 0;
}
// make mainDraw() fire every INTERVAL milliseconds
setInterval(mainDraw, INTERVAL);
// set our events. Up and down are for dragging,
// double click is for making new boxes
canvas.onmousedown = myDown;
canvas.onmouseup = myUp;
canvas.ondblclick = myDblClick;
canvas.onmousemove = myMove;
// set up the selection handle boxes
for (var i = 0; i < 8; i ++) {
var rect = new Box2;
selectionHandles.push(rect);
}
// add custom initialization here:
// add a large green rectangle
addRect(260, 70, 60, 65, 'rgba(0,205,0,0.7)');
// add a green-blue rectangle
addRect(240, 120, 40, 40, 'rgba(2,165,165,0.7)');
// add a smaller purple rectangle
addRect(45, 60, 25, 25, 'rgba(150,150,250,0.7)');
}
//wipes the canvas context
function clear(c) {
c.clearRect(0, 0, WIDTH, HEIGHT);
}
// Main draw loop.
// While draw is called as often as the INTERVAL variable demands,
// It only ever does something if the canvas gets invalidated by our code
function mainDraw() {
if (canvasValid == false) {
clear(ctx);
// Add stuff you want drawn in the background all the time here
ctx.drawImage(im,0,0);
// draw all boxes
var l = boxes2.length;
for (var i = 0; i < l; i++) {
boxes2[i].draw(ctx); // we used to call drawshape, but now each box draws itself
}
// Add stuff you want drawn on top all the time here
canvasValid = true;
}
}
// Happens when the mouse is moving inside the canvas
function myMove(e){
if (isDrag) {
getMouse(e);
mySel.x = mx - offsetx;
mySel.y = my - offsety;
// something is changing position so we better invalidate the canvas!
invalidate();
} else if (isResizeDrag) {
// time ro resize!
var oldx = mySel.x;
var oldy = mySel.y;
// 0 1 2
// 3 4
// 5 6 7
switch (expectResize) {
case 0:
mySel.x = mx;
mySel.y = my;
mySel.w += oldx - mx;
mySel.h += oldy - my;
break;
case 1:
mySel.y = my;
mySel.h += oldy - my;
break;
case 2:
mySel.y = my;
mySel.w = mx - oldx;
mySel.h += oldy - my;
break;
case 3:
mySel.x = mx;
mySel.w += oldx - mx;
break;
case 4:
mySel.w = mx - oldx;
break;
case 5:
mySel.x = mx;
mySel.w += oldx - mx;
mySel.h = my - oldy;
break;
case 6:
mySel.h = my - oldy;
break;
case 7:
mySel.w = mx - oldx;
mySel.h = my - oldy;
break;
}
invalidate();
}
getMouse(e);
// if there's a selection see if we grabbed one of the selection handles
if (mySel !== null && !isResizeDrag) {
for (var i = 0; i < 8; i++) {
// 0 1 2
// 3 4
// 5 6 7
var cur = selectionHandles[i];
// we dont need to use the ghost context because
// selection handles will always be rectangles
if (mx >= cur.x && mx <= cur.x + mySelBoxSize &&
my >= cur.y && my <= cur.y + mySelBoxSize) {
// we found one!
expectResize = i;
invalidate();
switch (i) {
case 0:
this.style.cursor='nw-resize';
break;
case 1:
this.style.cursor='n-resize';
break;
case 2:
this.style.cursor='ne-resize';
break;
case 3:
this.style.cursor='w-resize';
break;
case 4:
this.style.cursor='e-resize';
break;
case 5:
this.style.cursor='sw-resize';
break;
case 6:
this.style.cursor='s-resize';
break;
case 7:
this.style.cursor='se-resize';
break;
}
return;
}
}
// not over a selection box, return to normal
isResizeDrag = false;
expectResize = -1;
this.style.cursor='auto';
}
}
// Happens when the mouse is clicked in the canvas
function myDown(e){
getMouse(e);
//we are over a selection box
if (expectResize !== -1) {
isResizeDrag = true;
return;
}
clear(gctx);
var l = boxes2.length;
for (var i = l-1; i >= 0; i--) {
// draw shape onto ghost context
boxes2[i].draw(gctx, 'black');
// get image data at the mouse x,y pixel
var imageData = gctx.getImageData(mx, my, 1, 1);
var index = (mx + my * imageData.width) * 4;
// if the mouse pixel exists, select and break
if (imageData.data[3] > 0) {
mySel = boxes2[i];
offsetx = mx - mySel.x;
offsety = my - mySel.y;
mySel.x = mx - offsetx;
mySel.y = my - offsety;
isDrag = true;
invalidate();
clear(gctx);
return;
}
}
// havent returned means we have selected nothing
mySel = null;
// clear the ghost canvas for next time
clear(gctx);
// invalidate because we might need the selection border to disappear
invalidate();
}
function myUp(){
isDrag = false;
isResizeDrag = false;
expectResize = -1;
}
// adds a new node
function myDblClick(e) {
getMouse(e);
// for this method width and height determine the starting X and Y, too.
// so I left them as vars in case someone wanted to make them args for something and copy this code
var width = 100;
var height = 150;
addRect(mx - (width / 2), my - (height / 2), width, height, 'rgba(220,205,65,0.7)');
}
function invalidate() {
canvasValid = false;
}
// Sets mx,my to the mouse position relative to the canvas
// unfortunately this can be tricky, we have to worry about padding and borders
function getMouse(e) {
var element = canvas, offsetX = 0, offsetY = 0;
if (element.offsetParent) {
do {
offsetX += element.offsetLeft;
offsetY += element.offsetTop;
} while ((element = element.offsetParent));
}
// Add padding and border style widths to offset
offsetX += stylePaddingLeft;
offsetY += stylePaddingTop;
offsetX += styleBorderLeft;
offsetY += styleBorderTop;
mx = e.pageX - offsetX;
my = e.pageY - offsetY
}
// If you dont want to use <body onLoad='init()'>
// You could uncomment this init() reference and place the script reference inside the body tag
//init();
The error is:
<!DOCTYPE html>
<html>
<head>
<title>js</title>
</head>
<body onload='init2()'>
<canvas id="canvas" width="1000" height="1000">
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>
<!-- This image will be displayed on the canvas -->
<img id="myImage" src="https://image.slidesharecdn.com/bareconf-140329111624-phpapp02/95/draft-scientific-paper-1-638.jpg?cb=1396091812" style = "display: none">
<script src="canvas.js"></script>
</body>
</html>
Move you script tag to the end in the body.
Why you should move script to the end can be found here: https://stackoverflow.com/a/17106486/4713768
Move the assignment of the im variable
im = document.getElementById("myImage");
into the init2() function. Otherwise, it's executing when the script is loaded, before the rest of the DOM has been loaded.
See Why does jQuery or a DOM method such as getElementById not find the element?

Alert message and sprite issue

I'm making this mini-game where a ball keeps bouncing back & forth on the page with a movable sprite that the user controls (using the arrow keys). The object of the game is avoid the ball at all costs, but if you touch the ball, you lose & an alert message will pop up saying: "You lost, try again".
So my question is: how do I make it so that when the player touches the ball, an alert pops up. Are there any event handlers out there that can help with this?
Here is my code:
// BALL
var x = 0;
var y = 0;
var r = 10;
var dx = 4;
var dy = 8;
var WIDTH = 240;
var HEIGHT = 240;
var speed = 60;
var c=document.getElementById("myCanvas");
var cxt=c.getContext("2d");
function init() {
window.requestAnimationFrame(init, cxt)
draw();
}
function drawCircle(x,y,r) {
cxt.clearRect(0, 0, 240, 240);
cxt.beginPath();
cxt.arc(x, y, r, Math.PI * 2, false);
cxt.closePath();
cxt.fillStyle = "#006699";
cxt.fill();
}
function draw() {
var ball = drawCircle(x, y, r);
var link = document.getElementById("garen");
if (x + dx > WIDTH || x + dx < 0)
dx = -dx;
if (y + dy > HEIGHT || y + dy < 0)
dy = -dy;
x += dx;
y += dy;
}
init();
// SPRITE
$(document).keydown(function(e) {
switch (e.which) {
case 37:
$('#garen').stop().animate({
left: '-=50px'
}); //left arrow key
break;
case 38:
$('#garen').stop().animate({
top: '-=50px'
}); //up arrow key
break;
case 39:
$('#garen').stop().animate({
left: '+=50px'
}); //right arrow key
break;
case 40:
$('#garen').stop().animate({
top: '+=50px'
}); //bottom arrow key
break;
}
})

Javascript animation move diagonally and reverse

I'm having trouble trying to make an animation with JavaScript and the HTML5 canvas element.
I need to have an animation that starts in the bottom right corner of my canvas, which moves up diagonally to the top right hand corner and then reverses back the other direction to create a back and forth movement.
I can get my animation to move diagonally, but then I can't get it to change the direction.
I'm also having trouble getting the animation to start from the bottom no matter what I do.
The code below currently moves my animation top to bottom diagonally.
var context;
var x = 0;
var y = 0;
var stepx = 1.55;
var stepy = 1.55;
function setupAnimCanvas() {
var canvas = document.getElementById('assignmenttwoCanvas');
if (canvas.getContext) {
ctx = canvas.getContext('2d');
setInterval('draw();', 20);
img = new Image();
img.src = '../images/dragon.png';
//animation();
}
}
startPos = (500, 500);
endPos = (0, 0);
function draw() {
ctx.clearRect(0,0, 500,500);
drawBackground();
ctx.drawImage(img, y, x);
x += 3;
if(x < endPos){
x -= stepx;
y += stepy;
}
else if (y > endPos) {
x += stepx;
y -= stepy;
}
else {
endPos = startPos;startPos = y;
}
moveit();
setTimeout('mover()',25);
}
You can use a delta value for x and y. When the x or y position is at start or end you just reverse the delta by setting delta = -delta;
var dx = -3, dy = -3;
Then simply check for any criteria that would reverse the direction:
if (x < endPos[0] || x > startPos[0] || y < endPos[1] || y > startPos[1] ) {
dx = -dx;
dy = -dy;
}
See demo here:
http://jsfiddle.net/AbdiasSoftware/5dSSZ/
The essence of this (see comments and original source lines at fiddler-link)
var startPos = [500, 500];
var endPos = [0, 0];
var dx = -3, dy = -3;
var x = startPos[0], y = startPos[1];
function draw() {
ctx.clearRect(0, 0, 500, 500);
ctx.fillRect(x, y, 20, 20); //for demo as no image
x += dx;
y += dy;
if (x < endPos[0] || x > startPos[0] ||
y < endPos[1] || y > startPos[1] ) {
dx = -dx;
dy = -dy;
}
setTimeout(draw, 16); //requestAnimationFrame is a better choice
}

Bouncing Ball Game, Mouse Detect Event, JavaScript

I've already created a bouncing ball which bounces off the walls of the HTML5 Canvas that I have specified.
My goal is to make a "Game Over" screen appear when the pointer (mouse) hovers over the ball.
I have already searched and found some tutorials on mouse events in Javascript, but I'm not really sure how to implement them into my code =/.
Any help would be amazing.
<script>
var x = Math.floor((Math.random() * 600) + 1);
var y = Math.floor((Math.random() * 300) + 1);
var dx = 2;
var dy = 4;
function begin()
{
gameCanvas = document.getElementById('gameCanvas');
context = gameCanvas.getContext('2d');
return setInterval (draw, 20);
}
begin();
function draw()
{
context.clearRect(0,0,600,300);
context.fillStyle = "#0000FF";
context.beginPath();
context.arc(x,y,80,0,Math.PI*2,true);
context.closePath();
context.fill();
if (x < 0 || x > 600) dx=-dx
if (y < 0 || y > 300) dy=-dy;
x += dx;
y += dy;
}
gameCanvas.onmousemove = function (e)
{
var gameCanvas = e.target;
var context = gameCanvas.getContext('2d');
var coords = RGraph.getMouseXY(e);
}
You need to check if the mouse is hovering over the ball (hit test) by checking the distance of the ball to the cursor. If the distance is smaller than radius of the ball, it means that the mouse is over the ball.
Note, that you need to adjust the code below to your needs
Example:
var mouse_x = 10, mouse_y = 10, ball_x = 10, ball_y = 10, ball_radius = 70, is_game_over = false
if( Math.sqrt( Math.pow( mouse_x - ball_x, 2 ) + Math.pow( mouse_x - ball_x, 2 )) < ball_radius && !is_game_over ) {
console.log('Cursor is over the mouse, game over')
is_game_over = true
}
Do it for every frame update.
you can add onmousemove=SetValues() to your body element like so:
<body onmousemove=SetValues()>
and change your code to this:
<script>
var x = Math.floor((Math.random() * 600) + 1);
var y = Math.floor((Math.random() * 300) + 1);
var dx = 2;
var dy = 4;
var mouseX;
var mouseY;
function setValues(e)
{
mouseX = e.pageX; //get mouse x
mouseY = e.pageY; //get mouse y
}
function begin()
{
gameCanvas = document.getElementById('gameCanvas');
context = gameCanvas.getContext('2d');
return setInterval (draw, 20);
}
begin();
function draw()
{
context.clearRect(0,0,600,300);
context.fillStyle = "#0000FF";
context.beginPath();
context.arc(x,y,80,0,Math.PI*2,true);
context.closePath();
context.fill();
if (x < 0 || x > 600) dx=-dx
if (y < 0 || y > 300) dy=-dy;
x += dx;
y += dy;
//check if the mouse is on the ball
var centerX = x + 80; //center of ball
var centerY = y; //center of ball
if(Math.pow((mouseX - centerX), 2) + Math.pow((mouseY - centerY), 2) <= 6400){
//do whatever to end game
}
}

Categories