JavaScript moving objects from starting location to ending locations - javascript

I am taking a course online and I can't find help if am stuck..... I am using brackets and p5.js
these are the instructions i have:
Edit the spotlight object by creating x and y properties initialised to your location. Also endX and endY properties initialised to one of the Minsky's location.
Assign the other 2 spotlights and create the required properties.
Make the spotlight move perfectly from you towards the Minskys by adjusting the increments of x and y properties.
If you get everything correct then it will stop over the target.
Adjust x and y properties using
"+=" or "+"
"-=" or "-"
*/
(the minsky brothers are the targets i need the spotlight to be on, the "your location" is the start location)
i will copy and paste my code and the message i get when i submit :
// other variables, you don't need to change these
var img, spotlight_image;
var spotlight1;
var spotlight2;
var spotlight3;
function preload()
{
img = loadImage('scene.png');
spotlight_image = loadImage('spotlight.png')
}
function setup()
{
createCanvas(img.width, img.height);
//complete the initialisation of the first spotlight
//with properties x, y, endX and endY
spotlight1 = {
image: spotlight_image
x: 164,
y: 810,
endX: 780,
endY: 640,
}
//Initialize the second and third spotlights
spotlight2 = {
image: spotlight_image
x: 164,
y: 810,
endX: 480,
endY: 474,
}
spotlight3 = {
image: spotlight_image
x: 164,
y: 810,
endX:766,
endY: 290,
}
}
function draw()
{
image(img, 0, 0);
// alter the properties x and y of the objects below to animate the spotlights
spotlight.x += 1;
spotlight.y += 1;
////////// DO NOT CHANGE ANYTHING BELOW /////////////
var spotlights = [spotlight1, spotlight2, spotlight3];
var spotlightSize = 300;
blendMode(BLEND);
background(30);
for (var i = 0; i < spotlights.length; i++)
{
var spotlight = spotlights[i];
//stop the spotlight if it's near enough to endx and endy
if(spotlight)
{
//stop the spotlight if it goes off of the screen
spotlight.x = min(spotlight.x, 960);
spotlight.y = min(spotlight.y, 945);
spotlight.x = max(spotlight.x, 0);
spotlight.y = max(spotlight.y, 0);
if (abs(spotlight.endX - spotlight.x) < 50
&& abs(spotlight.endY - spotlight.y) < 50)
{
spotlight.x = spotlight.endX;
spotlight.y = spotlight.endY;
}
image(spotlight.image, spotlight.x-spotlightSize/2,
spotlight.y-spotlightSize/2, spotlightSize, spotlightSize);
}
}
blendMode(DARKEST);
image(img, 0, 0);
////////// DONOT CHANGE ANYTHING ABOVE /////////////
}
the message i get when submitting:
Error in compile
SyntaxError: Unexpected identifier
Blockquote

This is fairly easy to do. If I understand correctly, you want to move an object towards a point over a certain amount of time. All you have to do is get the range between the two X coordinates and the two Y coordinates, divide them by how many frames you want it to be moving for, and update its position by that amount every frame until it reaches its destination.

Related

TypeError: Cannot Read Property of Undefined Even Though I Defined It

I'm a beginner to JavaScript. I've looked through a few questions on here regarding "TypeError: ... undefined even though the property is defined" but their examples are either too dense for me to grasp or they realize they've incorrectly assigned something downstream. Here I think my example is quite simple, and I don't think I've incorrectly assigned anything.
I've defined position in my class MoveableObjects and when I call player = new MoveableObject(position, other params ...) I don't get any errors.
When I change this to player = new Sprite(position, other params ...) where Sprite extends MoveableObjects and then try to call a function inside Sprite it tells me position.x is undefined. I put console.log(player) immediately after the declaration and it does in fact show position as undefined, but I don't understand why it does since I've clearly defined it.
Here is the constructor of MoveableObjects
class MoveableObject {
constructor({ colorRGB, width, height, position, velocity}) {
this.width = width;
this.height = height;
this.position = position;
this.velocity = velocity;
this.colorRGB = colorRGB;
// If the side of the object is touching or beyond the side of the canvas it is flagged as bounded.
this.inUpLimit = false;
this.inDownLimit = false;
this.inLeftLimit = false;
this.inRightLimit = false;
// Translate the velocity into directional words
this.movingLeft = false;
this.movingRight = false;
this.movingUp = false;
this.movingDown = false;
}
Here is the constructor of Sprite and the draw() function it uses.
// Sprite represents moveable objects with an animated image.
class Sprite extends MoveableObject {
constructor({ imageSrc, numRows = 1, numCols = 1, spacing = 0, margin = 0, animationSpeed = 10, position, velocity}) {
super(position, velocity)
this.image = new Image() // Image can be a single image or a spritesheet.
this.image.src = imageSrc
this.numRows = numRows // # animation sequences in the spritesheet
this.numCols = numCols // # frames in an animation sequence
this.spacing = spacing // # pixels between each frame
this.margin = margin // # pixels between image border and sprite border. Vertical and horizontal margins should be equal.
this.animation = new Object()
this.animation.speed = animationSpeed // # times draw function is called before the next frame in the animation sequence is called.
this.animation.counter = 0 // # times the draw function has been called
this.animation.enabled = false // Whether or not the animation sequence is currently running
this.animation.row = 1; // The row of the current frame being drawn
this.animation.col = 1; // The column of the current frame being drawn
this.animation.firstRow = 1; // The row of the frame to initialize the animation loop on
this.animation.firstCol = 1; // The column of the frame to initialize the animation loop on
this.animation.lastRow = 1; // The row of the frame to restart the animation loop on
this.animation.lastCol = 1; // The column of the frame to restart the animation loop on
this.frame = new Object();
this.frame.width = 0; // Init image.onload
this.frame.height = 0; // Init image.onload
this.image.onload = () => { // Calculates width and height of animation frame based on numRows, numColumns, spacing, and margin
let imageWidth = this.image.width;
let spriteSheetWidth = imageWidth - (2 * this.margin);
let widthNoSpacing = spriteSheetWidth - this.spacing * (this.numCols - 1);
let frameWidth = widthNoSpacing / this.numCols;
let imageHeight = this.image.height;
let spriteSheetHeight = imageHeight - (2 * this.margin);
let heightNoSpacing = spriteSheetHeight - this.spacing * (this.numRows - 1);
let frameHeight = heightNoSpacing / numRows;
this.frame.width = frameWidth;
this.frame.height = frameHeight;
}
}
draw() {
// Draw the frame at the current row and column.
context.drawImage(
this.image, // the entire image being loaded
this.animation.col * this.frame.width, // sx, x coordinate to begin crop
this.animation.row * this.frame.height, // sy, y coordinate to begin crop
this.frame.width, // swidth, width of cropped image
this.frame.height, // sheight, height of cropped image
this.position.x, // x coordinate where to place image on canvas
this.position.y, // y coordinate where to place image on canvas
this.frame.width, // the width to stretch/shrink it to
this.frame.height // the height to stretch/shrink it to
)
Here I create a new MoveableObject with position defined and then console.log() it. It shows position to be what I set it to. I copy/paste that declaration and change "new MoveableObject" to "new Sprite" (with a new variable name of course) and print that, and it shows position is undefined:
// Initializers for main()
const gravity = 0.8;
const player = new Sprite({
imageSrc: './lib/img/template.png',
numRows: 21,
numCols: 4,
spacing: 0,
margin: 0,
position: {
x: 0,
y: 0
},
velocity: {
x: 0,
y: 0
}
})
console.log(player)
const enemy = new MoveableObject({
colorRGB: 'blue',
width: 50,
height: 150,
position: {
x: 150,
y: 50
},
velocity: {
x: 0,
y: 0
}
})
console.log(enemy)
const moveableObjects = [player, enemy];
// The main function of the script updates the game state every frame.
function main() {
// When the game starts the canvas, then player, then enemy are rendered.
context.fillStyle = 'black';
context.fillRect(0, 0, canvas.width, canvas.height);
player.draw();
enemy.draw();
The error is raised on player.draw() and reads "Uncaught TypeError: Cannot read properties of undefined (reading 'x')"
Does anyone understand why this is the case? It seems to me like the error is maybe produced by not properly extending my class or using super() incorrectly to pass attributes, but I haven't found an example that proves that.

Craftyjs canvas rotation

If I change the e1 attribute y to 1 or some other positive value this code works, but if the y is 0 or negative it fails. There are no errors but the shape does not appear. If I draw other kind of shapes, same kind of problem occurs. Anyway, rotation values such as 0, 90 and 271 work with y: 0. There is not such a problem with the x value. Why is that? Is it a bug related to Crafty.js?
<script>
Crafty.init(480,680, document.getElementById('test'));
Crafty.c("myComponent", {
init: function () {
this.requires("2D, Canvas");
this.bind("Draw", this._draw_me);
this.ready = true;
},
_draw_me: function (e) {
var ctx = e.ctx;
ctx.beginPath();
ctx.moveTo(e.pos._x, e.pos._y);
ctx.lineTo(e.pos._x + e.pos._w, e.pos._y);
ctx.lineTo(e.pos._x + e.pos._w/2, e.pos._y + e.pos._h);
ctx.lineTo(e.pos._x, e.pos._y);
ctx.fillStyle = "blue";
ctx.fill();
}
});
var e1 = Crafty.e("myComponent")
.attr({x: 100, y: 0, w: 60, h: 60, rotation:180})
.origin("center");
</script>
Set w and h before setting origin. Set the rotation origin before setting the rotation.
This should be clearly documented in the API documentation, I went ahead and opened an issue for that on Crafty's issue tracker.
If you set the origin after the rotation, things get messed up somehow, and the _draw_me function never gets called, as Crafty thinks the triangle sits outside the viewport (camera) and does not need to be drawn. (Observe what happens when you set Crafty.viewport.y = 100 - the triangle appears)
The following snippet works for me. The code sets w and h, origin & rotation, in that order.
Crafty.init();
Crafty.c("myComponent", {
init: function () {
this.requires("2D, Canvas");
this.bind("Draw", this._draw_me);
this.ready = true;
},
_draw_me: function (e) {
var ctx = e.ctx;
ctx.beginPath();
ctx.moveTo(e.pos._x, e.pos._y);
ctx.lineTo(e.pos._x + e.pos._w, e.pos._y);
ctx.lineTo(e.pos._x + e.pos._w/2, e.pos._y + e.pos._h);
ctx.lineTo(e.pos._x, e.pos._y);
ctx.fillStyle = "blue";
ctx.fill();
}
});
var e1 = Crafty.e("myComponent")
.attr({w: 60, h: 60})
.origin("center")
.attr({x: 100, y: 0, rotation: 180});
<script src="https://github.com/craftyjs/Crafty/releases/download/0.7.1/crafty-min.js"></script>

Using easelJS to free transform shapes on pressmove

I want to replicate the basic functionality of a free transform tool (no rotation), by dragging on the border of a easeljs Shape and adjusting the container to match it. I'm currently using the scaleX and scaleY properties and it sort of works but is not quite right.
If you do one scaling transformation it works pretty well. However if you release, then do another scaling transformation, it jumps very glitchily, and can occasionally break sending the x/y coordinates all the way to stage 0. Any help on this issue would be great!
http://jsfiddle.net/frozensoviet/dsczvrpw/13/
//circle
var circle = new createjs.Shape(new createjs.Graphics()
.beginFill("#b2ffb2")
.drawCircle(0, 0, 50));
circle.setBounds(0, 0, 50, 50);
//create the border as a seperate object
var cBorder = new createjs.Shape(new createjs.Graphics().setStrokeStyle(10)
.beginStroke("#000").drawCircle(0, 0, 50));
cBorder.setBounds(0, 0, 50, 50);
//add both to the container
circleContainer.addChild(circle);
circleContainer.addChild(cBorder);
var cWidth = circleContainer.getBounds().width;
var cHeight = circleContainer.getBounds().height;
//find initial mouse position relative to circle center
cBorder.on("mousedown", function (evt) {
//initial mouse pos
this.initial = {
x: Math.abs(-(circleContainer.x - evt.stageX)),
y: Math.abs(circleContainer.y - evt.stageY)
};
});
//set the relevant circle axis scale to ratio of mouse pos/initial mouse pos
cBorder.on("pressmove", function (evt) {
//current moouse pos
this.offset = {
x: Math.abs(-(circleContainer.x - evt.stageX)),
y: Math.abs(circleContainer.y - evt.stageY)
};
if (this.initial.x > this.initial.y) {
//sides
circleContainer.scaleX = this.offset.x / this.initial.x;
} else if (this.initial.x < this.initial.y) {
//top/bottom
circleContainer.scaleY = this.offset.y / this.initial.y;
} else {
//diagonals
circleContainer.scaleX = this.offset.x / this.initial.x;
circleContainer.scaleY = this.offset.y / this.initial.y;
}
stage.update();
});
The issue is your initial calculations don't account for the change in the scale of the circle. You would have to transform the coordinates using localToGlobal. Fortunately, there is an even easier way:
this.initial = {
x: Math.abs(evt.localX),
y: Math.abs(evt.localY)
};
You can also turn on ignoreScale on the border, which makes it not stretch:
createjs.Graphics().setStrokeStyle(10,null,null,null,true) // The 5th argument
Lastly, your bounds setting might work for your demo, but it is not correct. Your circle draws from the center, so it should be:
cBorder.setBounds(-25, -25, 50, 50);
Here is an updated fiddle: http://jsfiddle.net/tfy1sjnj/3/

Moving All Images In A Clipped Canvas

Ok so I have just looked into the Canvas element but I have hit a snag.
I found a demo that moves three images over the top of one another using arrow keys.
However, I clipped one of them and the underlying image does not move now even though the above clipped image does.
HTML:
<canvas id="parallax-canvas">
Sorry, your browser does not support HTML5 Canvas.
</canvas>
CSS:
.parallax-canvas {
width: 400px;
height: 300px;
}
JavaScript:
$(document).ready(function() {
var w = $("#parallax-canvas").width();
var h = $("#parallax-canvas").height();
var sky = new Image();
sky.src = "assets/img/sky.jpg";
var skydx = 2;
var skyx = 0;
var mountains = new Image();
mountains.src ="assets/img/mountains.png";
var mountainsdx = 10;
var mountainsx = 0;
var jeep = new Image();
jeep.src ="assets/img/jeep.png";
var jeepx = 100;
var jeepy = 210;
var jeepsx = 0;
var jeepsxWidth = 155;
var cntx = $("#parallax-canvas")[0].getContext("2d");
setInterval(draw, 10, cntx);
$(window).keydown(function(evt) {
switch (evt.keyCode) {
case 37: // Left arrow
if ((skyx + skydx) > skydx)
skyx -= skydx;
else
skyx = w;
if ((mountainsx + mountainsdx) > mountainsdx)
mountainsx -= mountainsdx;
else
mountainsx = 398;
if (jeepsx > 0)
jeepsx -= jeepsxWidth;
else
jeepsx = (jeepsxWidth*2);
break;
case 39: // Right arrow
if ((skyx + skydx) < (w - skydx))
skyx += skydx;
else
skyx = 0;
if ((mountainsx + mountainsdx) < (w - mountainsdx))
mountainsx += mountainsdx;
else
mountainsx = 0;
if (jeepsx < (jeepsxWidth*2))
jeepsx += jeepsxWidth;
else
jeepsx = 0;
break;
}
});
function draw(_cntx) {
drawRectangle(_cntx, 0, 0, w, h);
_cntx.drawImage(sky, skyx, 0, 300, 300, 0, 0, w, 300);
_cntx.beginPath();
_cntx.moveTo(0,300);
_cntx.lineTo(150,150);
_cntx.lineTo(300, 300);
_cntx.closePath();
_cntx.clip();
_cntx.drawImage(mountains, mountainsx, 0, 300, 300, 0, 0, w, 300);
_cntx.drawImage(jeep, jeepsx, 0, jeepsxWidth, 60, jeepx, jeepy, 155, 60);
}
function drawRectangle(_cntx, x, y, w, h) {
_cntx.beginPath();
_cntx.rect(x,y,w,h);
_cntx.closePath();
_cntx.fill();
_cntx.stroke();
}
});
The part where I added the clipping is this section:
function draw(_cntx) {
drawRectangle(_cntx, 0, 0, w, h);
_cntx.drawImage(sky, skyx, 0, 300, 300, 0, 0, w, 300);
_cntx.beginPath();
_cntx.moveTo(0,300);
_cntx.lineTo(150,150);
_cntx.lineTo(300, 300);
_cntx.closePath();
_cntx.clip();
_cntx.drawImage(mountains, mountainsx, 0, 300, 300, 0, 0, w, 300);
_cntx.drawImage(jeep, jeepsx, 0, jeepsxWidth, 60, jeepx, jeepy, 155, 60);
}
If you remove from and including the beginPath method to the clip method it will allow the three images to all move.
WHAT IS HAPPENING: The sky image does not move when pressing left and right arrow keys, the mountain and jeep are clipped but do move within the clipped region.
WHAT I WANT TO HAPPEN: The sky image to move as well as the mountain and jeep in the clipped region.
ALSO:
I would like to know how to move the clipped region with the arrow presses. What I mean is, at the moment there is a clipped region where by pressing left and right the images move but the clipped (cut out) region remains still. I would like to know (if possible) how to go about moving the clipped region with the arrow keys.
Demo being used: http://www.ibm.com/developerworks/web/library/wa-parallaxprocessing/
Unfortunately cannot setup a Fiddle as the images are not on the site so cannot be given a URL but the .zip is on the site and by copying and pasting the bottom part of code where their method is in the JavaScript file that is what I am getting.
Thanks for any help!
EDIT: Thanks Ken for your help with shortening code and efficiency. Nothing so far though has answered my initial questions of how to move the images and also the clipping positions.
You need to set a size for your canvas - don't use CSS to set the size of a canvas:
<canvas id="parallax-canvas" width=500 height=300>
Sorry, your browser does not support HTML5 Canvas.
</canvas>
Likewise you need to read the proper size from the canvas:
$(document).ready(function() {
var canvas = $("#parallax-canvas")[0];
var w = canvas.width;
var h = canvas.height;
...
The for each time you hit the cursor keys you need to redraw everything. The canvas doesn't know what is drawn into it - it's just a bunch of pixels so we need to provide the logic for updates ourselves.
Update seem as I missed you're doing the redraw from a setInterval loop so this doesn not apply so much, but I let the example stay as it will probably be a better approach as you only need to update when something is actually changing. A loop that redraws everything all the time will quickly drain batteries for example..
For example:
$(window).keydown(function(evt) {
switch (evt.keyCode) {
case 37: // Left arrow
if ((skyx + skydx) > skydx)
skyx -= skydx;
else
skyx = w;
if ((mountainsx + mountainsdx) > mountainsdx)
mountainsx -= mountainsdx;
else
mountainsx = 398;
if (jeepsx > 0)
jeepsx -= jeepsxWidth;
else
jeepsx = (jeepsxWidth*2);
draw(cntx );
break;
...
This you need to repeat for the other moves as well.
You will also run into problems with the way you are loading the images as loading is asynchronous. You need to handle loading by tapping into the onload handler:
var sky = new Image();
sky.onload = functionToHandleLoad;
sky.src = "assets/img/sky.jpg";
As you are loading many images you would need to count the images or use a bulk loader such as my YAIL loader.
For clipping it's important to use save/restore as currently browsers doesn't handle manual reset of clip regions that well:
function draw(_cntx) {
drawRectangle(_cntx, 0, 0, w, h);
_cntx.drawImage(sky, skyx, 0, 300, 300, 0, 0, w, 300);
_cntx.beginPath();
_cntx.moveTo(0,300);
_cntx.lineTo(150,150);
_cntx.lineTo(300, 300);
_cntx.closePath();
_cntx.save(); /// save current clip region
_cntx.clip();
_cntx.drawImage(mountains, mountainsx, 0, 300, 300, 0, 0, w, 300);
_cntx.drawImage(jeep, jeepsx, 0, jeepsxWidth, 60, jeepx, jeepy, 155, 60);
_cntx.restore(); /// reset clip
}
At the time of answering there where no fiddle available so I haven't checked the other parts of the code, but this should be a good start I think.
This function
function drawRectangle(_cntx, x, y, w, h) {
_cntx.beginPath();
_cntx.rect(x,y,w,h);
_cntx.closePath();
_cntx.fill();
_cntx.stroke();
}
can be simplified to:
function drawRectangle(_cntx, x, y, w, h) {
_cntx.fillRect(x, y, w, h);
_cntx.strokeRect(x, y, w, h);
}
No need to close path on a rect and beginPath is not needed with fillRect/strokeRect.

animation path problems

How would I make my object reach the end of the animation paths? I am making a basic pong game, but the ball stops early if it misses the paddle, It should reach the end of the path. Here is my code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf8">
<title> Rapahel test </title>
<script type="text/javascript" src="raphael.js">
</script>
</head>
<body>
<script type="text/javascript">
//create the canvas, which all the shapes are on
var paper = Raphael(0,0,500,500);
ballpath = '';
ballNum = 0;
//the paths the ball will follow, one at a time, starting from 0. which is the first in an array.
paths = ["M480, 180L35, 180", "M35, 180L480, 325", "M480, 325L35, 110", "M35, 110L480, 50", "M480, 50L35, 340", "M35, 340L480, 340", "M480, 340L35, 200", "M35, 200L35, 200"];
Raphael(function () {
ballpath = paper.path(paths[ballNum]).attr({stroke: "#0000ff", opacity: .3, "stroke-width": 1});
var ball = paper.circle(0, 0, 5).attr("fill", "rgba(255, 0, 0, 1)");
//the length variable (and arribute)
var len = ballpath.getTotalLength();
ball.onAnimation(function () {
var t = this.attr("transform");
});
paper.customAttributes.along = function (v) {
var point = ballpath.getPointAtLength(v * len);
return {
transform: "t" + [point.x, point.y] + "r" + point.alpha
};
};
ball.attr({along: 0});
//the variable rotateAlongThePath is true
var rotateAlongThePath = true;
//th function that actually makes the ball move
function run() {
//the path which the wall will follow
wallpath = paper.path("M480, 180L480, 380, M480, 380L480, 60, M480, 60L480, 340").attr({stroke: "#0000ff", opacity: .3, "stroke-width": 1});
//create a rectangle
var wall2 = paper.rect(0 - 50, 0 - 9, 100, 20).attr("fill", "rgba(0, 0, 255, 1)");
//the length variable (and arribute)
var wallLen = wallpath.getTotalLength();
//not sure aout these commands, they are to do with animation paths
wall2.onAnimation(function () {
var t = this.attr("transform");
});
paper.customAttributes.along2 = function (v2) {
var point2 = wallpath.getPointAtLength(v2 * wallLen);
return {
transform: "t" + [point2.x, point2.y] + "r" + point2.alpha
};
};
//set the wall's movemnt to 0
wall2.attr({along2: 0});
var collision = function(){
//find the paddle's height and width, the ball's center point, and AI Paddle's x position
var paddleheight = Math.round(paddle.getBBox().y + paddle.getBBox().height / 2);
var paddleWidth = Math.round(paddle.getBBox().x + paddle.getBBox().width / 2);
var ballcenterpoint = Math.round(ball.getBBox().y + ball.getBBox().height / 2);
var AIpaddle = Math.round(wall2.getBBox().x + wall2.getBBox().width / 2);
//the height from the center point of the paddle to the edge (heigh variance), finding the height of the top edge of the boundingbox (where the ball will colide with) by adding the centerpoint and height variance. finding the bottom edge by subtracting the centerpoint from the bounding box.
var heightvariance = pHeight;
var heightPlusboundingbox = paddleheight + heightvariance;
var heightMinusboundingbox = paddleheight - heightvariance;
//if the edge of the box is less than or equal to the center of the ball.
var balledge = Math.round(ball.getBBox().x + (ball.getBBox().width / 2) + 22);
//continue ballbounce is used for the if below; it equals: if the ball center is largerthan or equal to the height of the paddle minus its bounding box AND the center point is equal to or less than the height of the paddle plus the bounding box AND the center is equal to or greater than the width (extending the detected edge ofthe box by a few pixels so as to fix some collision problems) the if below will work.
console.log('Ball X: ', balledge);
console.log('AI X: ', AIpaddle);
console.log(balledge);
console.log(AIpaddle);
//the if
if(ballcenterpoint >= heightMinusboundingbox && ballcenterpoint <= heightPlusboundingbox || balledge >= AIpaddle){
//if the ball number is less than or equal to 6 it will increase theball number by one an change the ballpath to one in the array called paths[ballNum], the ball will then begin at the beginning of that path and be animated along it
if(ballNum <= 6){
ballNum++
ballpath = paper.path(paths[ballNum]).attr({stroke: "#0000ff", opacity: .3, "stroke-width": 1});
ball.attr({along: 0});
ball.animate({along: 1}, 2500, onanimationdone);
}
//if the ballNum is greater than 6 it will remove the ball (fixin the error of an infinite loop of theball just sitting the corner acting all boring and doing nothing)
}
else {
// ball.remove(); //- YOU LOSE
};
};
//animates the wall
wall2.animate({along2: 1}, 16200, function () {
});
//loops through all the ball paths
var onanimationdone = function () {
collision();
};
ball.animate({along: 1}, 2500, onanimationdone);
ball.attr({along: 0});
};
//create a rectangles
var pHeight = 100;
var pWidth = 20;
var paddle = paper.rect(10, 130, pWidth, pHeight);
paddle.attr("fill", "rgba(0, 0, 255, 1)");
var start = function () {
// storing original coordinates
this.originalY = this.attr("y");
this.attr({opacity: 0.9});
},
move = function (dx, dy) {
// moves the object up and down, when clicked and dragged
this.attr({y: this.originalY + dy});
},
up = function () {
// restoring state
this.attr({opacity: 1.0});
};
//runs the functions
paddle.drag(move, start, up);
run();
});
</script>
</body
</html>
I am new to JavaScript, I apologise if my code is a little hard to understand (this is my fourth day doing JavaScript).
Using raphael is valid for rendering your graphics, but I would suggest using the paths array for the ball's motion is not. If you are in fact trying to make a game you are best off having the ball store it's current position and velocity, and update these per frame via some some of timer.

Categories