JavaScript add too var in object every frame not working - javascript

So i have a object named Paddle and it has a var in it called posX and for some reason i cant just add one to it every frame but i can set its value, here is my coed
https://jsfiddle.net/noig/s9yxx13q/
var Paddle = function(sizeX, sizeY){
var posX, posY;
var sizeX, sizeY;
this.sizeX = sizeX;
this.sizeY = sizeY;
this.shape = new createjs.Shape();
}
Paddle.prototype.update = function(){
this.shape.x = this.posX;
};
var paddle1 = new Paddle(25, 75);
function init(){
var stage = new createjs.Stage("canvas");
//shape = new createjs.Shape();
paddle1.shape.graphics.beginFill("blue").drawRect( 15, 0, paddle1.sizeX, paddle1.sizeY);
stage.addChild(paddle1.shape);
stage.update();
createjs.Ticker.setFPS(60);
createjs.Ticker.addEventListener('tick', stage);
createjs.Ticker.addEventListener('tick', update);
}
function update(){
//paddle1.update(); This runs the code to make shape.x = posX
//paddle1.shape.x++; This moves paddle 1 every frame when not useing paddle.update();
//paddle1.posX = 50; This moves to the paddel50 units with paddle1.update();
//paddle1.posX++; This dose not move the paddle 1 unit every frame
//paddle1.posX += 1; This dose not move the paddle 1 unit ever frame
//paddle1.posX = paddle1.posX + 1; This dose not move the paddle 1 unit every frame
}
init();

It sounds like you want to update this.shape.x when you set this.posX. One way to do that is to define a property with getter/setter. Try adding this:
Object.defineProperty(Paddle.prototype, "posX", {
get: function() {return this.shape.x},
set: function(x) { this.shape.x = x; }
});
Object.defineProperty(Paddle.prototype, "posY", {
get: function() {return this.shape.y},
set: function(y) { this.shape.y = y; }
});
var Paddle = function(sizeX, sizeY){
this.sizeX = sizeX;
this.sizeY = sizeY;
this.shape = new createjs.Shape();
}
Object.defineProperty(Paddle.prototype, "posX", {
get: function() {return this.shape.x},
set: function(x) { this.shape.x = x; }
});
Object.defineProperty(Paddle.prototype, "posY", {
get: function() {return this.shape.y},
set: function(y) { this.shape.y = y; }
});
var paddle1 = new Paddle(25, 75);
function init(){
var stage = new createjs.Stage("canvas");
//shape = new createjs.Shape();
paddle1.shape.graphics.beginFill("blue").drawRect( 15, 0, paddle1.sizeX, paddle1.sizeY);
stage.addChild(paddle1.shape);
stage.update();
createjs.Ticker.setFPS(60);
createjs.Ticker.addEventListener('tick', stage);
createjs.Ticker.addEventListener('tick', update);
}
function update(){
paddle1.posX++;
}
init();
<script src="https://code.createjs.com/createjs-2015.05.21.min.js"></script>
<canvas id="canvas"></canvas>

Related

(toggle) function is not defined

I'm trying to use a button to toggle the audio for a P5 oscillator on and off (because as I understand it, WebAudio API stuff requires an interaction in browsers now for audio to play).
Before the setup I have:
var button;
In the function setup I have:
button = createButton("audio on/off");
button.mousePressed(toggle);
button.position(32, 180);
In function toggle I have:
if (!playing()) {
osc.start();
//playing = true; } else {
osc.stop();
//playing = false; }
It keeps giving me the error message
Uncaught ReferenceError: toggle is not defined (sketch: line 45)"
Why do I keep getting this? Any help would be greatly appreciated.
The full sketch.js code is:
var button;
var stepX;
var stepY;
let osc;
function setup() {
createCanvas(displayWidth, displayHeight);
noCursor();
noStroke();
colorMode(HSB, width, height, 100);
reverb = new p5.Reverb();
delay = new p5.Delay();
osc = new p5.Oscillator();
osc.setType('sine');
reverb.process(osc, 5, 5);
osc.start();
// delay.process() accepts 4 parameters:
// source, delayTime, feedback, filter frequency
// play with these numbers!!
delay.process(osc, 0.6, 0.3, 1000);
// play the noise with an envelope,
// a series of fades ( time / value pairs )
var t = 10
let text = createP("s-p-e-c-t-r-u-m");
text.position(30, 30);
text.style("font-family", "monospace");
text.style("background-color", "#FFFFFF");
text.style("color", "#F20FD7");
text.style("font-size", "12pt");
text.style("padding", "10px");
let texty = createP("move mouse to control the <br>sine-wave theramin.<br><br>x axis = pitch 30-3000hz<br>y axis = volume quiet-loud)");
texty.position(32, 80);
//texty.style("background-color", "#FFFFFF");
texty.style("font-family", "monospace");
texty.style("color", "#FFFFFF");
texty.style("font-size", "10pt");
button = createButton("audio on/off");
button.mousePressed(toggle);
button.position(32, 180);
}
function draw() {
let pitch = map(mouseX, 0, width, 30, 3000);
let volume = map(mouseY, 0, height, 1, 0);
background(200);
osc.freq(pitch);
osc.amp(volume);
stepX = mouseX + 2;
stepY = mouseY + 2;
for (var gridY = 0; gridY < height; gridY += stepY) {
for(var gridX = 0; gridX < width; gridX += stepX) {
fill(gridX, height - gridY, 100);
rect(gridX, gridY, stepX, stepY);
}
}
function toggle() {
if (!playing) {
osc.start();
playing = true;
} else {
osc.stop();
playing = false;
}
}
}
toggle is declared in scope of draw:
function draw() {
// [...]
function toggle() {
// [...]
}
}
Move it out of draw, top solve the issue:
function draw() {
// [...]
}
function toggle() {
// [...]
}
See the example:
var button;
var stepX;
var stepY;
let osc;
function setup() {
createCanvas(displayWidth, displayHeight);
noCursor();
noStroke();
colorMode(HSB, width, height, 100);
reverb = new p5.Reverb();
delay = new p5.Delay();
osc = new p5.Oscillator();
osc.setType('sine');
reverb.process(osc, 5, 5);
osc.start();
// delay.process() accepts 4 parameters:
// source, delayTime, feedback, filter frequency
// play with these numbers!!
delay.process(osc, 0.6, 0.3, 1000);
// play the noise with an envelope,
// a series of fades ( time / value pairs )
var t = 10
let text = createP("s-p-e-c-t-r-u-m");
text.position(30, 30);
text.style("font-family", "monospace");
text.style("background-color", "#FFFFFF");
text.style("color", "#F20FD7");
text.style("font-size", "12pt");
text.style("padding", "10px");
let texty = createP("move mouse to control the <br>sine-wave theramin.<br><br>x axis = pitch 30-3000hz<br>y axis = volume quiet-loud)");
texty.position(32, 80);
//texty.style("background-color", "#FFFFFF");
texty.style("font-family", "monospace");
texty.style("color", "#FFFFFF");
texty.style("font-size", "10pt");
button = createButton("audio on/off");
button.mousePressed(toggle);
button.position(32, 180);
}
function draw() {
let pitch = map(mouseX, 0, width, 30, 3000);
let volume = map(mouseY, 0, height, 1, 0);
background(200);
osc.freq(pitch);
osc.amp(volume);
stepX = mouseX + 2;
stepY = mouseY + 2;
for (var gridY = 0; gridY < height; gridY += stepY) {
for(var gridX = 0; gridX < width; gridX += stepX) {
fill(gridX, height - gridY, 100);
rect(gridX, gridY, stepX, stepY);
}
}
}
function toggle() {
if (!playing) {
osc.start();
playing = true;
} else {
osc.stop();
playing = false;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/addons/p5.sound.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/addons/p5.dom.js"></script>
Try assigning your functions to variables. Without doing that all your functions will be hoisted to the top of the file at run time. Also make sure you declare toggle before you use it!

javascript: applyForce function error

This is from a Khanacademy project - I was wondering why when I try to apply my repulsion force from my buglight to each of the flies why does it return __env__.flies[j].applyForce is not a function.
I had been messing around with this and can't get it to accept that force. Also when I try to make the glow of the buglight within that function change by adding an amount and then removing an amount it looks like it is happening too fast because it is only showing the maximum glow amount.
CODE:
// I created a light over where the mouse is and the flies (random start poisitions) are drawn toward the light, but I included some randomness to their movements to add some variation to their paths, the flies are repelled from the buglight using a repulsion force:
var Mover = function() {
this.position = new PVector (random(width),random(height));
this.velocity = new PVector (0,0);
this.acceleration = new PVector (0,0);
this.mass = 1;
};
Mover.prototype.update = function () {
var mouse = new PVector(mouseX,mouseY);
var dist = PVector.sub(mouse, this.position);
var randomPush = new PVector(random(-1,1),random(-1,1));
dist.normalize();
dist.mult(0.4);
this.acceleration = dist;
this.acceleration.add(randomPush);
this.velocity.add(this.acceleration);
this.velocity.limit(9);
this.position.add(this.velocity);
};
Mover.prototype.display = function () {
strokeWeight(7);
stroke(0, 0, 0);
point(this.position.x,this.position.y);
strokeWeight(5);
point(this.position.x - 3,this.position.y -3);
point(this.position.x + 3,this.position.y -3);
};
var Buglight = function (){
this.position = new PVector (random(width-50),random(height-80));
this.velocity = new PVector (0,0);
this.acceleration = new PVector (0,0);
this.glow = 70;
this.mass = 20;
this.G = 1;
};
Buglight.prototype.update = function() {
noStroke();
fill(39, 131, 207,90);
ellipse(this.position.x+20,this.position.y+35,this.glow,this.glow);
};
Buglight.prototype.repulsion = function(fly) {
var force = PVector.sub(this.position,fly.position);
var distance = force.mag();
distance = constrain(distance, 4.0, 20.0);
force.normalize();
var strength = -1 *(this.G * this.mass * fly.mass) / (distance * distance);
force.mult(strength);
return force;
};
Buglight.prototype.display = function() {
noStroke();
fill(5, 170, 252);
rect(this.position.x+15,this.position.y,10,60);
fill(0, 0, 0);
noStroke();
rect(this.position.x-10,this.position.y+60,60,10,10);
rect(this.position.x,this.position.y,10,60);
rect(this.position.x+30,this.position.y,10,60 );
quad(this.position.x,this.position.y,
this.position.x-10,this.position.y+20,
this.position.x+50,this.position.y+20,
this.position.x+40,this.position.y);
};
Buglight.prototype.checkEdges = function () {
};
var flies = [];
for (var i = 0; i < 4; i++){
flies[i] = new Mover();
}
var buglight = new Buglight();
var fly = new Mover();
draw = function() {
background(71, 71, 71);
strokeWeight(56);
stroke(219, 247, 8,100);
fill(255, 238, 0);
ellipse(mouseX,mouseY,20,20);
buglight.update();
buglight.display();
for (var j = 0; j < flies.length; j++) {
var blueForce = buglight.repulsion(flies[j]);
flies[j].applyForce(blueForce);
flies[j].update();
flies[j].display();
}
};
There is no applyForce function on your Mover class. Something is missing I feel.

Loading Images from a Canvas

I'm trying to make a game in HTML5 and I'm having trouble loading image assets. My issue is that the onload event of the code isn't firing and so the boolean isn't changing.
var c = document.getElementById("gamearea");
var gs = c.getContext("2d");
var one_x = 0;
//Sprite Loading//
function sprite(src,x, y, width, height, frames, levels) {
this.sprite = Image();
this.sprite.src = src;
this.x = x;
this.y = y;
this.w = width;
this.h = height;
this.f = frames;
this.l = levels;
this.cf = 0;
this.cl = 0;
this.loaded = false;
this.src = src;
}
sprite.prototype.draw = function () {
if (this.loaded) {
document.getElementById("ass").innerHTML = "Ass";
gs.drawImage(this.src, this.x, this.y);
}
}
dog = new sprite("/images/sDog.png", 10, 10, 10, 10, 1, 1);
dog.sprite.onload = function () {
alex.loaded = true;
}
setInterval(alex.draw, 30);
I would suggest putting the onload event before the set event for your dog sprite image object. I see that you set everything in the constructor, but I would suggest against that.
In you current code you object is being loaded before the line that initializes the onload event.
I have seen this a lot with loading images, I would do something like this.
function sprite(src,x, y, width, height, frames, levels) {
var self = this;
self.sprite = new Image();
self.init = function(){
self.sprite.src = src;
self.x = x;
self.y = y;
self.w = width;
self.h = height;
self.f = frames;
self.l = levels;
self.cf = 0;
self.cl = 0;
self.loaded = false;
self.src = src;
}
}
dog = new sprite();
dog.sprite.onload = function () {
alex.loaded = true;
}
dog.init("/images/sDog.png", 10, 10, 10, 10, 1, 1);
setInterval(alex.draw, 30);
or, to get a little fancier
function sprite(src,x, y, width, height, frames, levels, onLoad) {
var self = this;
self.sprite = new Image();
self.sprite.onload = function(){
onLoad();
}
self.sprite.src = src;
self.x = x;
self.y = y;
self.w = width;
self.h = height;
self.f = frames;
self.l = levels;
self.cf = 0;
self.cl = 0;
self.loaded = false;
self.src = src;
}
dog = new Sprite("/images/sDog.png", 10, 10, 10, 10, 1, 1, function(){
alex.loaded = true;
});
setInterval(alex.draw, 30);
after looking at your fiddle
var c = document.getElementById("gamearea");
var gs = c.getContext("2d");
var one_x = 0;
//Sprite Loading//
function sprite(src, x, y, width, height, frames, levels, loaded) {
var self = this;
self.sprite = new Image();
self.sprite.onload = function(){
self.loaded = true;
}
self.sprite.src = src;
self.x = x;
self.y = y;
self.w = width;
self.h = height;
self.f = frames;
self.l = levels;
self.cf = 0;
self.cl = 0;
self.loaded = false;
self.src = src;
self.update = function () {
one_x += 1;
gs.fillStyle = "white";
gs.fillRect(0, 0, 1000, 10000);
gs.fillStyle = "black";
gs.fillRect(one_x, 20, 10, 10);
}
self.draw = function (){
if (self.loaded) {
document.getElementById("ass").innerHTML = "Ass";
gs.drawImage(self.sprite, self.x, self.y);
}
}
}
dog = new sprite("http://www.bit-101.com/blog/wp-content/uploads/2009/05/ball.png", 10, 10, 10, 10, 1, 1);
setInterval(dog.draw, 30);
You're missing new here:
this.sprite = Image();
Try:
this.sprite = new Image();
Also make sure that the image file actually exists in the given location.

HTML5/CANVAS :Mouse event issue

I'm facing a problem right now, the mouse event doesn't seem to work. I have a button sprite and a player sprite , and I want that when I click on the button , the player should move butit doesn't, well here's mycode:
var canvas = document.getElementById("canvas_1");
ctx = canvas.getContext("2d");
canvas.addEventListener('mousedown', doMouseDown, true);
var X = 100;
var Y = 0;
var x = 0;
var y = 0;
var player = new Image();
var butt = new Image();
player.src = 'images/player.png';
butt.src = 'images/right.png';
player.onload = function () {
ctx.drawImage(player, x, 0);
}
butt.onload = function () {
ctx.drawImage(butt, X, Y);
}
update = function () {
ctx.clearRect(0, 0);
ctx.drawImage(player, x, y);
}
setInterval(update, 1000 / fps.getFPS());
var fps = {
startTime: 0,
frameNumber: 0,
getFPS: function () {
this.frameNumber++;
var d = new Date().getTime(),
currentTime = (d - this.startTime) / 1000,
result = Math.floor((this.frameNumber / currentTime));
if (currentTime > 1) {
this.startTime = new Date().getTime();
this.frameNumber = 0;
}
return result;
}
};
function doMouseDown(event) {
var mousePos = getMousePos(canvas, event);
if ((mousePos.x >= X && mousePos.x <= X + butt.width) && (mousePos.y >= Y && mousePos.y <= Y + butt.height)) {
x += 4;
}
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
what you are doing is like you clicked, doMouseDown function called and end.
and you needed to call this function many times to get animation.so,
you can try like
if clicked var clicked=true
and put this below code in loop
if (clicked){
x+=4
}

I can't get mouse input in my HTML5 game

I'm trying to get mouse input in my game; any help would be appreciated.
I call the event listeners in my init() function, and I have both my mouseMoved() and mouseClicked() functions. But I just haven't been able to get any response.
(I was asked to make a jsFiddle for this project, so here it is. It's not rendering the images, for some reason. But once there's input, there should be text on the top left the shows the mouse coordinates. Also, when you click on the canvas, you should get an alert.)
var canvasBg = document.getElementById('canvasBg');
var ctxBg = canvasBg.getContext('2d');
var canvasEntities = document.getElementById('entities');
var entitiesCtx = canvasEntities.getContext('2d');
var isPlaying = false;
var player;
var enemy;
var mouseX, mouseY;
var playerImg = new Image();
playerImg.src = 'http://placekitten.com/g/50/50';
var enemyImg = new Image();
enemyImg.src = 'http://placehold.it/50x50';
window.onload = init;
var requestAnimFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
// main functions
function init() {
console.debug('init()');
player = new Entity(250, // xpos
225, // ypos
0, // xd
0, // yd
3, // speed
50, // width
50, // height
playerImg, // imgSrc
true); // player?
enemy = new Entity(500,225,0,0,1,25,25,enemyImg,false);
canvasBg.addEventListener('mousemove', mouseMoved, false);
canvasBg.addEventListener('click', mouseClicked, false);
startLoop();
}
function loop() {
// console.debug('game loop');
if(isPlaying){
update();
draw();
requestAnimFrame(loop);
}
}
function startLoop() {
isPlaying = true;
loop();
}
function stopLoop() {
isPlaying = false;
}
function clearAllCtx() {
ctxBg.clearRect(0, 0, canvasBg.width, canvasBg.height);
Entity.clearCtx();
}
function draw(){
clearAllCtx();
player.draw();
enemy.draw();
}
function update(){
player.update();
}
// end of main functions
// input handling
function mouseMoved(e) {
mouseX = e.layerX - canvasBg.offsetLeft;
mouseY = e.layerY - canvasBg.offsetTop;
document.getElementById('mouseCoors').innerHTML = 'X: ' + mouseX + ' Y: ' + mouseY;
}
function mouseClicked(e) {
alert('You clicked the mouse!');
}
// end of input handling
// Entity functions
function Entity(xpos, ypos, xd, yd, speed, width, height, imagesrc, player) {
this.xpos = xpos;
this.ypos = ypos;
this.xd = xd;
this.yd = yd;
this.speed = speed;
this.width = width;
this.height = height;
this.imagesrc = imagesrc;
this.player = player;
}
Entity.clearCtx = function(){
entitiesCtx.clearRect(0,0,canvasBg.width,canvasBg.height);
};
Entity.prototype.draw = function () {
entitiesCtx.drawImage(this.imagesrc, this.xpos, this.ypos);
};
Entity.prototype.update = function () {
this.xpos += this.xd;
this.ypos -= this.yd;
};
// end of Entity functions
So theres a few things going on, first the fiddle loading was set incorrectly, once I changed it to no wrap in body everything works.
The actual issue you're having is due to the background canvas being under the entities canvas, so it cant get any of the mouse events.
One solution would be to use pointer-events and set it to none like so pointer-events: none on the entities canvas.
Live Demo
#entities {
margin: -500px auto;
pointer-events: none;
}
Another option if you need wider browser support is to have the entities canvas capture the mouse events instead.
Live Demo of Option 2

Categories

Resources