How to detect overlap in Phaser.js? - javascript

I am new to Phaserjs, and I am trying to make a shooting game. I want the damage function to fire when a bullet touches plane2, that is the green plane. Can somone please tell me what am I doing wrong here?
Here is my code:
var config = {
type: Phaser.AUTO,
width: 800,
height: 800,
parent:"game",
physics: {
default: 'arcade',
arcade: {
debugging:true,
gravity: {y: 0}
}
},
scene: {
preload: preload,
create: create,
update: update
}
};
var plane1
var plane2
var hp;
var botHp;
function preload (){
this.load.setBaseURL('https://shoot.abaanshanid.repl.co/assets');
this.load.image("bg", "bg.jpg");
this.load.image("plane1", "plane1.png");
this.load.image("plane2", "plane2.png");
this.load.image("bullet", "bullet.png");
}
function create (){
this.background = this.add.image(400, 400, "bg");
plane1 = this.physics.add.sprite(400,700,"plane1");
plane2 = this.physics.add.sprite(400,100,"plane2");
plane1.enableBody = true;
}
function update(){
keys = this.input.keyboard.createCursorKeys();
if (keys.left.isDown) {
plane1.x = plane1.x - 7.5;
}else if(keys.right.isDown){
plane1.x = plane1.x + 7.5;
}else if(keys.space.isDown){
var bullet = this.physics.add.sprite(plane1.x,600,"bullet");
bullet.enableBody = true;
setInterval(function(){
bullet.y = bullet.y - 25;
},50);
this.physics.overlap(bullet,plane2,this.damage);
}
}
function damage(){
console.log("less HP")
}
var game = new Phaser.Game(config);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/3.54.0/phaser.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/3.54.0/phaser-arcade-physics.min.js"></script>
</head>
<body>
<div id="game"></div>
<script defer src="script.js"></script>
</body>
</html>
Here is the link to the game if needed https://shoot.abaanshanid.repl.co/

This works:
this.physics.add.overlap(bullet,plane2,damage);
but its kinda laggy. Id try to destroy bullet on impact and i also found:
this.physics.add.collider(bullet,plane2,damage);

Related

I want to convert paper.js Examples from paperscript to javascript

I am Japanese and I apologize for my unnatural English, but I would appreciate it if you could read it.
I learned how to convert paperscript to javascript from the official documentation.
Its means are as follows
Change the type attribute of the script tag to text/paperscript. <script type="text/paperscript" src="./main.js"></script>
Enable Paperscope for global use.  paper.install(window)
Specify the target of the canvas. paper.setup(document.getElementById("myCanvas"))
Write the main code in the onload window.onload = function(){ /* add main code */ }
Finally, add paper.view.draw()
The onFrame and onResize transforms as follows. view.onFrame = function(event) {}
onMouseDown, onMouseUp, onMouseDrag, onMouseMove, etc. are converted as follows. var customTool = new Tool(); customTool.onMouseDown = function(event) {};
I have tried these methods, but applying these to the Examples on the paper.js official site does not work correctly.
The following code is the result of trying these.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="https://unpkg.com/paper"></script>
<script type="text/javascript" src="./main.js"></script>
<title>Document</title>
</head>
<body>
<canvas id="myCanvas"></canvas>
</body>
</html>
paper.install(window);
console.log("run test")
var myCanvas = document.getElementById("myCanvas")
var customTool = new Tool();
window.onload = function(){
paper.setup(myCanvas)
var points = 25;
// The distance between the points:
var length = 35;
var path = new Path({
strokeColor: '#E4141B',
strokeWidth: 20,
strokeCap: 'round'
});
var start = view.center / [10, 1];
for (var i = 0; i < points; i++)
path.add(start + new Point(i * length, 0));
customTool.onMouseMove=function(event) {
path.firstSegment.point = event.point;
for (var i = 0; i < points - 1; i++) {
var segment = path.segments[i];
var nextSegment = segment.next;
var vector = segment.point - nextSegment.point;
vector.length = length;
nextSegment.point = segment.point - vector;
}
path.smooth({ type: 'continuous' });
}
customTool.onMouseDown=function(event) {
path.fullySelected = true;
path.strokeColor = '#e08285';
}
customTool.onMouseUp=function(event) {
path.fullySelected = false;
path.strokeColor = '#e4141b';
}
view.draw();
}
The original paperscript can be found here.
What is the problem with this code?
Thank you for reading to the end!
The var vector in the for loop is not getting the correct values in your code. Change the math operators and it will work like the paperjs demo.
Math operators (+ - * /) for vector only works in paperscript. In Javascript, use .add() .subtract() .multiply() .divide(). see http://paperjs.org/reference/point/#subtract-point
// paperscript
segment.point - nextSegment.point
// javascript
segment.point.subtract(nextSegment.point)
Here's a working demo of your example
paper.install(window);
console.log("run test")
var myCanvas = document.getElementById("myCanvas")
var customTool = new Tool();
window.onload = function() {
paper.setup(myCanvas)
var points = 15; //25
// The distance between the points:
var length = 20; //35
var path = new Path({
strokeColor: '#E4141B',
strokeWidth: 20,
strokeCap: 'round'
});
var start = view.center / [10, 1];
for (var i = 0; i < points; i++) {
path.add(start + new Point(i * length, 0));
}
customTool.onMouseMove = function(event) {
path.firstSegment.point = event.point;
for (var i = 0; i < points - 1; i++) {
var segment = path.segments[i];
var nextSegment = segment.next;
//var vector = segment.point - nextSegment.point;
var vector = segment.point.subtract(nextSegment.point);
vector.length = length;
//nextSegment.point = segment.point - vector;
nextSegment.point = segment.point.subtract(vector);
}
path.smooth({
type: 'continuous'
});
}
customTool.onMouseDown = function(event) {
path.fullySelected = true;
path.strokeColor = '#e08285';
}
customTool.onMouseUp = function(event) {
path.fullySelected = false;
path.strokeColor = '#e4141b';
}
view.draw();
}
html,
body {
margin: 0
}
canvas {
border: 1px solid red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="https://unpkg.com/paper"></script>
<!-- you can add this back in -->
<!-- <script type="text/javascript" src="./main.js"></script> -->
<title>Document</title>
</head>
<body>
<!-- set any size you want, or use CSS/JS to make this resizable -->
<canvas id="myCanvas" width="600" height="150"></canvas>
</body>
</html>

i am using paper js to make patatap clone but keep getting an error

i am doing a course on udemy, the course name is web developer bootcamp by colt steele, in lecture 239 when i am adding the object 'keyData' an error shows in my console.my code is this.`
<!DOCTYPE html>
<html>
<head>
<title>Circles</title>
<script type="text/javascript" src="paper-full.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/howler/2.1.3/howler.js"></script>
<link rel="stylesheet" type="text/css" href="circles.css">
<script type="text/paperscript" canvas="myCanvas">
var keyData = {
a: {
color: "purple",
sound: new Howl({
src: ['sounds/bubbles.mp3']
});
},
s: {
color: "green",
sound: new Howl({
src: ['sounds/clay.mp3']
});
},
d: {
color: "yellow",
sound: new Howl({
src: ['sounds/confetti.mp3']
});
}
}
var circles = [];
function onKeyDown(event){
if(keyData[event.key]){
var maxPoint = new Point(view.size.width, view.size.height);
var randomPoint = Point.random();
var point = maxPoint * randomPoint;
var newCircle = new Path.Circle(point, 500);
newCircle.fillColor = keyData[event.key].color;
keyData[event.key].sound.play();
circles.push(newCircle);
}
}
function onFrame(event){
for(var i = 0; i < circles.length; i++){
circles[i].scale(.9);
circles[i].fillColor.hue += 1;
}
}
<!-- alert(view.size); this will give an alert showing the max width and max height of the screen-->
<!-- alert(view.center); this will give an alert showing the center of the screen-->
</script>
</head>
<body>
<canvas id="myCanvas" resize></canvas>
</body>
</html>
The error only comes when the object 'keyData' is typed. This is the error.`
paper-full.js:15726 Uncaught SyntaxError: Unexpected token (8:6)
at raise (paper-full.js:15726)
at unexpected (paper-full.js:16366)
at expect (paper-full.js:16362)
at parseObj (paper-full.js:16829)
at parseExprAtom (paper-full.js:16799)
at parseExprSubscripts (paper-full.js:16730)
at parseMaybeUnary (paper-full.js:16716)
at parseExprOps (paper-full.js:16682)
at parseMaybeConditional (paper-full.js:16669)
at parseMaybeAssign (paper-full.js:16655)
` The main problem that persists is that when i type the object the error comes .Please help. Thank you.
You have extra ; in your keyData code.
Here is the corrected code.
<!DOCTYPE html>
<html>
<head>
<title>Circles</title>
<script type="text/javascript" src="paper-full.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/howler/2.1.3/howler.js"></script>
<link rel="stylesheet" type="text/css" href="circles.css">
<script type="text/paperscript" canvas="myCanvas">
var keyData = {
a: {
color: 'purple',
sound: new Howl({
src: ['sounds/bubbles.mp3']
})
},
s: {
color: 'green',
sound: new Howl({
src: ['sounds/clay.mp3']
})
},
d: {
color: 'yellow',
sound: new Howl({
src: ['sounds/confetti.mp3']
})
}
};
var circles = [];
function onKeyDown(event) {
if (keyData[event.key]) {
var maxPoint = new Point(view.size.width, view.size.height);
var randomPoint = Point.random();
var point = maxPoint * randomPoint;
var newCircle = new Path.Circle(point, 500);
newCircle.fillColor = keyData[event.key].color;
keyData[event.key].sound.play();
circles.push(newCircle);
}
}
function onFrame(event) {
for (var i = 0; i < circles.length; i++) {
circles[i].scale(.9);
circles[i].fillColor.hue += 1;
}
}
<!-- alert(view.size); this will give an alert showing the max width and max height of the screen-->
<!-- alert(view.center); this will give an alert showing the center of the screen-->
</script>
</head>
<body>
<canvas id="myCanvas" resize></canvas>
</body>
</html>

How do I make my Phaser game shoot more than one arrow?

I'm making an archery game in JavaScript using the Phaser framework. So far I've got where the arrow goes and hits the target, but if you want the arrow to shoot again, you have to reload the page. How do I make it so that it can shoot more than once?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>TSA Video Game</title>
<script src="//cdn.jsdelivr.net/npm/phaser#3.11.0/dist/phaser.js"></script>
<style type="text/css">
body {
margin: 0;
}
</style>
</head>
<body>
<script type="text/javascript">
var config = {
type: Phaser.AUTO,
width: 800,
height: 600,
physics: {
default: 'arcade'
},
scene: {
preload: preload,
create: create,
update: update,
render: render
}
};
//Start the game
var game = new Phaser.Game(config);
function preload ()
{
this.load.image('sky', 'assets/sky.png');
this.load.image('archer', 'assets/archer.png');
this.load.image('target', 'assets/target.png');
this.load.image('ground', 'assets/ground.png');
this.load.image('rings', 'assets/rings.png');
this.load.image('arrow', 'assets/arrow.png');
}
function create ()
{
//Load all the images
this.add.image(400, 300, 'sky');
this.add.image(200, 200, 'ground');
this.add.image(530, 365, 'target');
this.add.image(300, 100, 'rings');
//Create the archer/player
this.player = this.physics.add.sprite(100, 410, 'archer');
//Create the arrow to shoot
this.arrow = this.physics.add.sprite(100, 430, 'arrow');
//Get keypresses
this.cursors = this.input.keyboard.createCursorKeys();
//Assign input for spacebar
this.spacebar = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE);
}
function update ()
{
//Declare constants for movement
const moveAmt = 1500;
const moveYamt = 0;
this.player.setDrag(2000);
//Move the player left or right
if (this.cursors.right.isDown)
this.player.setVelocityX(moveAmt);
if (this.cursors.left.isDown)
this.player.setVelocityX(-moveAmt);
//Rotation of the player
if (this.cursors.up.isDown && this.player.angle > -45) {
this.player.angle -= 1;}
if (this.cursors.down.isDown && this.player.angle < 0) {
this.player.angle += 1;}
//Shooting with the spacebar
if (Phaser.Input.Keyboard.JustDown(this.spacebar)) {
this.arrow.setVelocityX(moveAmt);
this.arrow.setVelocityY(moveYamt);
}
//Stop the arrow once it hits the bullseye
if (this.arrow.x > 480) {
this.arrow.x = 480;
this.arrow.setVelocityX(0);
this.arrow.setVelocityY(0);
}
}
function render() {
}
</script>
</body>
</html>
I've tried creating three arrows, and nesting another if statement inside the "if (Phaser.Keyboard.Justdown" statement, but that didn't work.
You need to be able to create an Array of arrows.
This is a quick, get-you-going, example:
In your create() function
this.arrows = []; // Create your array
And later:
if (Phaser.Input.Keyboard.JustDown(this.spacebar)) {
let arrow = this.physics.add.sprite(100, 430, 'arrow'); // Create a new arrow
arrow.setVelocityX(moveAmt); // get it moving
arrow.setVelocityY(moveYamt);
this.arrows.push(arrow); // save it in the array
}
Yes you need much more code, but this should help.
Then you need to cycle through the arrows that are in motion and update each of them

Admob Phonegap build Stuck

Ok I have an application on the market for testing purposes and Im trying to implement admob ads I have my account for banner ads and everything the only thing is that I dont know how to set it up I need help please this is the sample application. Thank you
Mostly what i need i need to show banner ads on my title screen game screen and game over screen Ive tried several tutorials none seem to get me anywhere so thats why i decided maybe here one of you can help Me with this.
This is the html file----------------------------------------------------
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="UTF-8-8">
<meta name="viewport" content="user-scalable=0, initial-scale=1,minimum-scale=1, maximum-scale=1, width=device-width, minimal-ui=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
<script type="text/javascript" src="js/phaser.js"></script>
<script src="js/stateTitle.js"></script>
<script src="js/characters.js"></script>
<style>
body {
padding: 0px;
margin: 0px;
background: black;
c
}
</style>
</head>
<body>
<script src="js/stateOver.js"></script>
<script src="js/main.js"></script>
</body>
</body>
</html>
----------------------------------------------------------------------------_
Main.js
var score =0;
var highscore =0;
var highScoreText;
var scoreText;
var MainState = {
//load the game assets before the game starts
preload: function () { /////////////////////////////preload
this.load.image('background', 'assets/city.png');
this.load.image('bird', 'assets/bird.png');
game.load.image('pipe', 'assets/pipe.png');
},
//executed after everything is loaded
create: function () {
this.background = this.game.add.sprite(0, 0, 'background');
highScoreText = this.game.add.text(600, 40, 'HS: ' + highscore, {
font: '25px Arial',
fill: 'black'
});
/////Bird///////////////////////////////////////////////////
this.bird = this.game.add.sprite(100, 200, 'bird');
game.physics.startSystem(Phaser.Physics.ARCADE);
game.physics.arcade.enable(this.bird);
this.bird.body.gravity.y = 1000;
var spaceKey = game.input.keyboard.addKey(
Phaser.Keyboard.SPACEBAR);
game.input.onDown.add(this.jump, this); //////touch screen jump
spaceKey.onDown.add(this.jump, this);
this.bird.body.collideWorldBounds=true;
this.bird.body.immovable= true;
///////////////////////////////////////////////////////Pipes
this.pipes = game.add.group();
//timer
this.timer = game.time.events.loop(1400, this.addRowOfPipes, this); /////////////timer for pipes
///////////////////////////////////////////////////////Score
this.score = -1;
this.labelScore = game.add.text(20, 20, "0",
{ font: "30px Arial", fill: "black" });
},
// this is execated multiple times per second
update: function () { //////////////////////////////////////////////////update
if (this.bird.y < 0 || this.bird.y > 480)
game.state.start("StateOver");
///Collision
game.physics.arcade.overlap(
this.bird, this.pipes, this.restartGame, null, this);
////////////////////////////////////////////////////////////////////////// Highscore counter
highScoreText.text = 'HS: ' + this.currentHighScore;
{
if (this.score > this.currentHighScore)
{
this.currentHighScore = this.score;
}
}
},
jump: function () {
//this is for so the bird wount fly once dead
if (this.bird.alive == false)
return;
///sound
///this.jumpSound.play();
// Add a vertical velocity to the bird
this.bird.body.velocity.y = -350;
// Jump Animation
var animation = game.add.tween(this.bird);
// Change the angle of the bird to -20° in 100 milliseconds
animation.to({angle: -20}, 100);
// And start the animation
animation.start();
game.add.tween(this.bird).to({angle: -20}, 100).start();
},
restartGame: function () {
// Start the 'main' state, which restarts the game
game.state.start(game.state.current);
///Hit pipe Null
game.physics.arcade.overlap(
this.bird, this.pipes, this.hitPipe, null, this);
},
addRowOfPipes: function() {
var hole = Math.floor(Math.random() * 5) + 1; ///Math.floor(Math.random() * 5) + 1;
for (var i = 0; i < 10 ; i++) ///// (var i = 0; i < 8; i++)
if (i != hole && i != hole + 1) ///// if (i != hole && i != hole + 1)
this.addOnePipe(440, i * 50 ); ///// 640 starting point of pipe 240 point of down ////this.addOnePipe(480, i * 60 + 10);
///Score for pipes
this.score += 1;
this.labelScore.text = this.score;
},
addOnePipe: function(x, y) {
var pipe = game.add.sprite(x, y, 'pipe');
this.pipes.add(pipe);
game.physics.arcade.enable(pipe);
pipe.body.velocity.x = -200;
pipe.checkWorldBounds = true;
pipe.outOfBoundsKill = true;
},
hitPipe: function() {
// If the bird has already hit a pipe, do nothing
// It means the bird is already falling off the screen
if (this.bird.alive == false)
return;
else {
game.state.start("StateOver");
}
// Set the alive property of the bird to false
this.bird.alive = false;
// Prevent new pipes from appearing
game.time.events.remove(this.timer);
// Go through all the pipes, and stop their movement
this.pipes.forEach(function(p){
p.body.velocity.x = 0;
}, this);
},
};
// Initilate the Phaser Framework
var game = new Phaser.Game(480, 640, Phaser.AUTO);
game.state.add("main", MainState);
game.state.add("stateTitle", stateTitle);
game.state.add("StateOver", StateOver);
game.state.add("characters", characters);
game.state.start("stateTitle");
-----------------------------------------------------------------------------
Game over screen stateover.js
var StateOver={
preload:function()
{
game.load.spritesheet('button', 'assets/button.png', 215, 53, 8);
game.load.image("title", "assets/title.png");
game.load.image("game", "assets/extra/gameover.png");
},
create:function()
{
this.title = game.add.tileSprite(0, game.height-640,game.width, 640, 'title');
this.title.autoScroll(-100,0);
this.btnPlayAgain=game.add.button(110,400,'button',this.playAgain,this,2,3,2);
this.btnMainMenu=game.add.button(110,300,'button',this.mainMenu,this,4,5,4);
this.btnStore=game.add.button(110,200,'button',this.Store,this,6,7,6);
this.game.add.sprite (118, 100, "game");
highScoreText = this.game.add.text(130, 150, 'HS: ' + highscore, {
font: '25px Arial',
fill: 'black'
});
},
playAgain:function()
{
game.state.start("main");
},
mainMenu:function()
{
game.state.start("stateTitle");
},
Store:function()
{
game.state.start("characters");
},
update:function()
{
highScoreText.text = 'HIGHSCORE: ' + localStorage.getItem("highscore");
{
if (this.score > localStorage.getItem("highscore"))
{
localStorage.setItem("highscore", this.score);
}
}
},
};
This is the main title screen
var stateTitle={
preload:function()
{
game.load.image("logo", "assets/extra/Logo.png");
game.load.image("title", "assets/title.png");
game.load.spritesheet('button', 'assets/button.png', 215, 53, 8);
},
create:function()
{
this.title = game.add.tileSprite(0, game.height-640,game.width, 640, 'title');
this.title.autoScroll(-100,0);
this.btnStart=game.add.button(110,400,'button',this.startGame,this,0,1,1);
this.btnStore=game.add.button(110,480,'button',this.Store,this,6,7,6);
this.logo = game.add.sprite(60, 150, 'logo');
},
startGame:function()
{
game.state.start("main");
},
Store:function()
{
game.state.start("characters");
},
update:function()
{
},
};
Html with sample
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="UTF-8-8">
<meta name="viewport" content="user-scalable=0, initial-scale=1,minimum-scale=1, maximum-scale=1, width=device-width, minimal-ui=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
<script type="text/javascript" src="js/phaser.js"></script>
<script src="js/stateTitle.js"></script>
<script src="js/characters.js"></script>
<style>
body {
padding: 0px;
margin: 0px;
background: black;
c
}
</style>
</head>
<body>
<script src="js/stateOver.js"></script>
<script src="js/main.js"></script>
<script type="text/javascript">
function onDeviceready() {
admob.createBannerView({publisherId: "ca-app-pub-XXXXXXXXXXXXXXXX/BBBBBBBBBB"});
}
document.addEventListener('deviceready', onDeviceready, false);
</script>
</body>
</html>
Firstly add admob plugin then just add below lines to your html file:
<script>
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
if (AdMob)
AdMob.prepareInterstitial({
adId : 'ca-app-pub-xxx/yyy',
autoShow : false
});
if (AdMob)
AdMob.createBanner({
adId : 'ca-app-pub-xxx/yyy',
position : AdMob.AD_POSITION.BOTTOM_CENTER,
autoShow : true,
overlap : true
});
}
</script>
You can change the place of the banner; use TOP_CENTER (I am not sure about this) instead of BOTTOM_CENTER.
Ok SOOOOO many tries alone I was able to fix this by simply inserting the extra needed plugins. Internet connection etc. BOOOOOOOOOOOOOOM Fixed any questions ask.

HTML5 Canvas Image doesn't move

I have a problem. I'm using HTML5 and Javascript to draw a box onto a canvas. This box is supposed to move up and down, but after it gets rendered for the first time, it doesn't want to re-render at the new position. This is the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="sl" lang="sl">
<head>
<title>Spletna stran Portfolio - Domaca stran</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
<link rel="stylesheet" href="css/style.css" type="text/css" media="all" />
<script>
var isMoving = true;
var gradienty = 0;
var gradientheight = 100;
var gradientyVel = 1;
var gradientImage = new Image();
gradientImage.src = "grafika/gradient.gif";
function main() {
var c = document.getElementById("menuCanvas");
var ctx = c.getContext("2d");
ctx.drawImage(gradientImage, 0, gradienty);
if(isMoving == true) {
gradienty += gradientyVel;
if((gradienty+gradientheight)==c,height || gradienty<=0) {
gradientyVel *= -1;
}
}
}
function mainLoop() {
setInterval(main(), 10);
}
</script>
</head>
<body onload="mainLoop()">
<canvas id="menuCanvas" width="195" height="400"></canvas>
</body>
</html>
I have no clue why the box isn't moving. It's like after I draw it for the first time it won't draw again the next time. Also, I use mainLoop() function as my main loop. Every 10 miliseconds I basically call the main() function, which does the drawing and the logic.
Any help would be much appreciated. :)
A few coding problems:
You need to give your image time to load, then start the animation
var gradientImage = new Image();
gradientImage.onload=function(){
setInterval(main, 20);
}
gradientImage.src = "house16x16.png";
setInterval takes in a function pointer (no parentheses):
setInterval will fire only as fast as 16ms, so your 10ms value is too small
setInterval(main, 20);
Here's revised code and a Demo: http://jsfiddle.net/m1erickson/U6K9j/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var c=document.getElementById("menuCanvas");
var ctx=c.getContext("2d");
var isMoving = true;
var gradienty = 0;
var gradientheight = 100;
var gradientyVel = 1;
var gradientImage = new Image();
gradientImage.onload=function(){
setInterval(main, 20);
}
gradientImage.src = "house16x16.png";
function main() {
ctx.clearRect(0,0,c.width,c.height);
ctx.drawImage(gradientImage, 0, gradienty);
if(isMoving == true) {
gradienty += gradientyVel;
if((gradienty+gradientheight)==c.height || gradienty<=0) {
gradientyVel *= -1;
}
}
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="menuCanvas" width=300 height=300></canvas>
</body>
</html>
You're calling main and then passing the RESULT to setInterval. Just change
function mainLoop() {
setInterval(main(), 10);
}
to
function mainLoop() {
setInterval(main, 10);
}
That'll get you started, but you'll also need to clear the canvas in between draws. (As you'll notice if you run this)

Categories