Why does my object method not register? Javascript - javascript

here is the code for my project:
'_' is a selector method.
'update' is run on an interval of 0.1
'init' creates the
'Ball' is the object I'm trying to create
'ball.set()' is the method that is not working.
var width = window.innerWidth/3;
var height = window.innerHeight-60;
var balls = [];
var id;
function rand(min, max) {
return (Math.random() * (max - min)) + min;
}
function run(){
init();
}
function init(){
document.write("<div style='width:"+width+"px;height:"+height+"px;' id='container'></div>");
new Ball(width/2-12.5, height/2-12.5, rand(-2, 2), rand(-2, 2), 1);
id = setInterval(update, 0.1);
}
function _(elem){
return document.getElementById(elem);
}
function update(){
for(var b in balls){
b.set();
}
}
function Ball(x, y, vx, vy, ind){
this.x = x;
this.y = y;
this.vx = vx;
this.vy = vy;
this.ind = ind;
balls[this.ind] = this;
_("container").innerHTML+=("<div style='top:"+y+"px;left:"+x+"px;' class='ball' id='ball"+this.ind+"'></div>");
this.deleteBall = function () {
_('ball'+this.ind).outerHTML = "";
balls[this.ind] = null;
};
this.set = function(){
this.x += this.vx;
this.y += this.vy;
var elem = _("ball"+this.ind);
elem.style.left = this.x + 'px';
elem.style.top = this.y + 'px';
};
}
run();
I'm trying to make a Ball object for a JS game I'm making. The only problem is Google Chrome is giving me an error:
Uncaught TypeError: b.set is not a function
at update (ballgame.js:29)
update # ballgame.js:29
What am I doing wrong?

I don't know the complete requirement, but I found the cause for this issue.The problem is with the line
balls[this.ind] = this;
Assume for the first time the constructor is called with 'ind' value of 5. This will set balls[5]=this object. Now 'balls' array length becomes 6 and balls[0] through balls[4] will contain value as 'undefined'.
Now in 'update' method, when you iterate through balls array, as balls[0] through balls[4] are undefined, you get the error
Uncaught TypeError: b.set is not a function

Related

Error "Uncaught TypeError" when changing this object propety- JavaScript

I am learning about objects and prototypes in JavaScript and I got stuck.
My aim is to create an object which then gets drawn onto a page. I have created another prototype constructor so later the this specific created object can be moved on a page however it doesn't work and I don't know how to progress further with it
here is my JS:
var Bunny = function (x, y) {
this.x = x;
this.y = y;
}
Bunny.prototype.drawBunny = function () {
var bunnyImage = document.createElement('img');
bunnyImage.src = "https://64.media.tumblr.com/tumblr_m06yweMXBl1qaajuxo1_500.gif";
bunnyImage.style.position = "absolute";
bunnyImage.style.left = this.x + "px";
bunnyImage.style.top = this.y + "px";
document.getElementsByTagName("body")[0].appendChild(bunnyImage);
}
Bunny.prototype.moveRight = function() {
this.x += 5;
this.bunnyImage.style.left = this.x + "px";
this.bunnyImage.style.top = this.y + "px";
}
and then in console log (this works):
var sunflower = new Bunny(200, 200);
sunflower.drawBunny();
but when I write this in console log:
sunflower.moveRight();
I get this error:
Uncaught TypeError: this.bunnyImage is undefined
pointing at this.bunnyImage in moveRight() function
Define "It doesn't work" (this statement alone is not enough to help). In your case, the console says :
Uncaught TypeError: Cannot read property 'style' of undefined
Indeed, this.bunnyImage is undefined. You forgot to store it in your function with this.bunnyImage = bunnyImage;
var Bunny = function(x, y) {
this.x = x;
this.y = y;
}
Bunny.prototype.drawBunny = function() {
var bunnyImage = document.createElement('img');
bunnyImage.src = "https://64.media.tumblr.com/tumblr_m06yweMXBl1qaajuxo1_500.gif";
bunnyImage.style.position = "absolute";
bunnyImage.style.left = this.x + "px";
bunnyImage.style.top = this.y + "px";
this.bunnyImage = bunnyImage;
document.getElementsByTagName("body")[0].appendChild(bunnyImage);
}
Bunny.prototype.moveRight = function() {
this.x += 5;
this.bunnyImage.style.left = this.x + "px";
this.bunnyImage.style.top = this.y + "px";
}
var sunflower = new Bunny(200, 200);
sunflower.drawBunny();
sunflower.moveRight();
var Bunny = function (x, y) {
this.x = x;
this.y = y;
}
Bunny.prototype.drawBunny = function () {
this.bunnyImage = document.createElement('img');
this.bunnyImage.src = "https://64.media.tumblr.com/tumblr_m06yweMXBl1qaajuxo1_500.gif";
this.bunnyImage.style.position = "absolute";
this.bunnyImage.style.left = this.x + "px";
this.bunnyImage.style.top = this.y + "px";
document.getElementsByTagName("body")[0].appendChild(this.bunnyImage);
}
Bunny.prototype.moveRight = function(delta = 5) {
this.x += delta;
this.bunnyImage.style.left = this.x + "px";
this.bunnyImage.style.top = this.y + "px";
}
var sunflower = new Bunny(200, 0);
sunflower.drawBunny();
// Lets dance
setInterval(() => {
sunflower.moveRight(200 * (.5 - Math.random()))
}, 200)

How do i define this method in vue.js?

I am attempting to create a JavaScript Text Animation but i am getting particleArray is undefined
i am not sure how to resolve the issue i have tried moving the code from the mounted method since it would load before being defined but same results.
export default {
data : function (){
return {
particleArray: null,
x:null,
y:null,
radius: 150,
vuedata: null,
}
},
class Particle{
constructor(x, y){
this.x = x + 100;
this.y = y;
this.size = 3;
this.baseX = this.x;
this.baseY = this.y;
this.density = (Math.random() *30) + 1;
}
draw(){
ctx.fillStyle = '#fff';
ctx.beginPath();
ctx.ard(this.x, this.y, this.size,0,Math.PI * 2);
ctx.closePath();
ctx.fill();
}
}
function init(){
this.particleArray = [];
particleArray.push(new Particle(50,50));
}
The answer is this.particleArray.push(new Particle(50,50));
this.particleArray = []; assigns the data property particleArray the value [].
particleArray.push(new Particle(50,50)); attempts a method on a local variable that does not exist.

Javascript constructor variable NAN inside function

I've tried to trace through all the possibilities of what's happening, but I'm learning Javascript so it has to be something I just don't know. The specific issue lies within the pongGame constructor/function; however, I have included my entire code just encase it is necessary. I would assume that, inside my gameLoop function which declared within the pongGame constructor, the variable pongGame.delta would be equal to 10; For, that is what I declared it to be. However, it is equal to NaN. What exactly is the issue that is happening here? Thanks :)
var keys = [false, false, false, false];
var cavnas = document.getElementById("canvas");
var context = cavnas.getContext("2d");
(function() {
startUp();
})();
function startUp() {
resize();
window.addEventListener("resize", resize);
var game = new pongGame();
game.start();
}
function resize() {
document.getElementById("canvas").width = window.innerWidth;
document.getElementById("canvas").height = window.innerHeight;
}
function pongGame() {
this.delta = 10;
this.lastTime = 0;
this.ball = new ball();
this.start = function() {
this.gameLoop();
}
this.update = function() {
this.ball.update();
}
this.render = function() {
context.clearRect(0, 0, window.innerWidth, window.innerHeight);
this.ball.render();
}
var pongGame = this;
this.gameLoop = function(timestamp) {
console.log(pongGame.delta); // 10
pongGame.delta += timestamp - pongGame.lastTime;
while (pongGame.delta > (1000 / 60)) {
pongGame.update();
pongGame.delta -= (1000/60);
}
pongGame.render();
pongGame.lastTime = timestamp;
requestAnimationFrame(pongGame.gameLoop);
}
}
function paddle() {
}
function ball() {
this.x = 1;
this.y = 1;
this.xspeed = 1;
this.yspeed = 1;
this.size = 10;
this.update = function() {
if (this.x == 0 || this.x == window.innerWidth - this.size) {
this.xspeed = -this.xspeed;
}
if (this.y == 0 || this.y == window.innerHeight - this.size) {
this.yspeed = -this.yspeed;
}
this.x += this.xspeed;
this.y += this.yspeed;
}
this.render = function() {
context.beginPath();
context.arc(this.x, this.y, this.size, 0, Math.PI * 2);
context.fill();
}
}
The first time you call gameLoop you do not pass a timestamp so this expression pongGame.delta += timestamp - pongGame.lastTime; sets delta to NAN the first time its ran and then all subsequent runs (which have a timestamp) since its already NAN.
Maybe call it with 0 the first time
this.start = function() {
this.gameLoop(0);
}

From interval to requestAnimationFrame

Revisiting one of my old experiments. I'm using an interval to rotate an element. Now I want to change the interval to rAF. I tried to rewrite the Rotation.start method a few times, but I couldn't succeed. Since I'm new to this requestAnimationFrame thing, I don't know what else to try.
Relevant JS code:
function Rotation(mass) {
this.mass = mass;
this.angle = 0;
this.velocity = 1;
this.fps = 1000/25; // for interval
this.handler = null;
this.rotate = function () {
// when called from rAF "this" refers to window, method fails
this.angle = (this.angle + this.velocity) % 360;
var transform = "rotate(" + this.angle + "deg)";
this.mass.elm.style.webkitTransform = transform;
};
this.start = function () {
var rotation = this; // this = Rotation
rotation.handler = setInterval(function () {
// inside the interval "this" refers to window
// that's why we set rotation to "this" at the beginning
// so we can access the Rotation obj
rotation.rotate();
}, rotation.fps);
/* requestAnimationFrame(rotation.rotate); */
};
}
Fiddle (full code)
You can bind the value of this using the bind() method
function Rotation(mass) {
this.mass = mass;
this.angle = 0;
this.velocity = 1;
this.handler = null;
this.rotate = function () {
this.angle = (this.angle + this.velocity) % 360;
var transform = "rotate(" + this.angle + "deg)"
this.mass.elm.style.webkitTransform = transform;
//call bind on this.rotate so we can properly associate this
window.requestAnimationFrame(this.rotate.bind(this));
};
this.start = function () {
//then just start the animation by using this.rotate()
this.rotate();
};
}
Working JSFiddle: http://jsfiddle.net/gvr16mcL/

Javascript add function to object

Hello there stackoverflow people,
I'm messing around with HTML5 and Javascript and I'm trying to add a function to an object in javascript, just like a function is added to a class in C#.
Here is my javascript (I know this doesn't work)
function Hero()
{
this.xPos = 100;
this.yPos = 100;
this.image = new Image();
this.image.src = "Images/Hero.png";
}
function MoveHero( xSpeed, ySpeed )
{
xPos += xSpeed;
yPos += ySpeed;
}
Now in my main loop function like so
function main()
{
canvas.fillStyle = "#555555";
canvas.fillRect( 0, 0, 500, 500);
canvas.drawImage( hero.image, hero.xPos, hero.yPos );
hero.MoveHero(1,1);
}
Now this ofcourse tells me that
"Uncaught TypeError: Object #<Hero> has no method 'MoveHero'"
How would I link the function so I could use
hero.MoveHero(x,y);
If anyone could help me out it would be awesome.
P.S. I am declaring my hero variable globally like so
var hero = new Hero();
is that ok?
You can;
Hero.prototype.MoveHero = function( xSpeed, ySpeed )
{
this.xPos += xSpeed;
this.yPos += ySpeed;
}
function Hero()
{
// add other properties
this.MoveHero = function( xSpeed, ySpeed )
{
this.xPos += xSpeed;
this.yPos += ySpeed;
}
}

Categories

Resources