Multiple instance of same object - javascript

I'm trying to make a shooting game with the view from above with javascript, here is the bullet object:
var Bullet = function(pId, bX, bY, bdX, bdY, bdT){
this.id = pId;
this.x = bX;
this.y = bY;
this.dx = bdX;
this.dy = bdY;
this.dt = bdT;
this.start = function (){
this.valInt=setInterval(this.id+".muovi()", this.dt);
}
this.muovi = function(){
this.x += this.dx;
this.y += this.dy;
this.img.style.left = this.x+'px';
this.img.style.top = this.y+'px';
}
this.img = new Image();
this.img.src = "./img/sprites/bullet/bullet.png"
this.img.style.position = "fixed"
this.img.style.left = this.x + "px"
this.img.style.top = this.y + "px"
document.body.appendChild(this.img)
this.start();
}
and then in the main js I instance it like this when an onkeydown event happen
function shootDx(){
b = new Bullet('b',pgX,pgY,1,0,1);
proj.push(b);
}
I want all the bullets inside an array so i can manage them better,there's a logic problem because when i shoot more than one time it doesn't create another instance, therefore i can't put them in the array and work on it, how can i afford that ?

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)

Why does my object method not register? 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

JS object inheritance with attributes

Im trying to get a very simple inheritance pattern for my Project going, extending from a base class into a specialized class. However, my specialized class's attributes are being overwritten by the parent's attributes.
Why is that and how can i fix it ?
thanks,
function Ship(className, x, y){
this.className = className;
this.x = x;
this.y = y;
this.speed = 0;
}
function Corvette(className, x, y){
this.className = className;
this.x = x;
this.y = y;
this.speed = 100;
Ship.call(this, className, x, y)
}
Corvette.prototype = Object.create(Ship.prototype);
var ship = new Ship("Biggie", 50, 50);
var corvette = new Corvette("Smallish", 50, 50);
console.log(Corvette.className) // "Smallish" - correct via parameter.
console.log(Corvette.speed) // should be 100, is 0 - not correct, "static" from parent attribute
console.log(Corvette.constructor.name) // Ship
Why you have the same properties in the child object which are already in the parent's?
I suggest you to do
function Ship(className, x, y, speed = 0) {
this.className = className;
this.x = x;
this.y = y;
this.speed = speed;
}
function Corvette(className, x, y, speed = 100) {
Ship.call(this, className, x, y, speed);
}
Corvette.prototype = Object.create(Ship.prototype);
Corvette.prototype.constructor = Corvette;
var ship = new Ship("Biggie", 50, 50);
var corvette = new Corvette("Smallish", 50, 50);
console.log(corvette.className) // "Smallish" - correct via parameter.
console.log(corvette.speed) // should be 100, is 0 - not correct, "static" from parent attribute
console.log(corvette.constructor.name) // Ship
and if your browser supports some features of ES6 use this feature ES6 classes.
class Ship { // And also Ship is an abstractionm so you can use `abstract` keyword with it
constructor(className, x, y, speed = 0) {
this.className = className;
this.x = x;
this.y = y;
this.speed = speed;
}
}
class Corvette extends Ship {
constructor(className, x, y, speed = 100) {
super(className, x, y, speed);
}
}
var ship = new Ship("Biggie", 50, 50);
var corvette = new Corvette("Smallish", 50, 50);
console.log(corvette.className) // "Smallish" - correct via parameter.
console.log(corvette.speed) // should be 100, is 0 - not correct, "static" from parent attribute
console.log(corvette.constructor.name) // Ship
You only need to move Ship.call(this, className, x, y) at the start of Corvette function.
Also, next time, before posting code, check it is correct, you wrote console.log(Corvette) instead of console.log(corvette)
Another thing: you do not need to repeat params you do not want to overwrite
function Ship(className, x, y){
this.className = className;
this.x = x;
this.y = y;
this.speed = 0;
}
function Corvette(className, x, y){
Ship.call(this, className, x, y)
this.speed = 100;
}
Corvette.prototype = Object.create(Ship.prototype);
var ship = new Ship("Biggie", 50, 50);
var corvette = new Corvette("Smallish", 50, 50);
console.log(corvette.className)
console.log(corvette.speed)
console.log(corvette.constructor.name)
You should invoke the parentclass contructor first and then override the properties, this way the properties set by Corvette will not be changed by the parent class i.e.:
function Corvette(className, x, y){
Ship.call(this, className, x, y)
this.speed = 100;
}

Unable to create a new instance in javascript

the following is my code,
function hostile(x, y) {
this.speed = 1;
this.health = 100;
this.x = x;
this.y = y;
this.height = 32;
this.width = 32;
this.isDead = false;
this.direction = 0;
this.move = function(){
context.clearRect(0,0,canvas1.width,canvas1.height);
if (this.x > canvas.width - 64) {
this.y += 10;
this.direction = 0;
}
if (this.x < 0) {
this.y += 10;
}
if (this.direction === 1) {
this.x += this.speed;
} else {
this.x -= this.speed;
}
if (this.x < 0) {
this.direction = 1;
}
if (this.y > 420) {
//this might have to be changed
this.x = 600;
}
}
};
//CREATING AN INSTANCE OF HOSTILE, THIS ISN'T WORKING FOR MULTIPLE INSTANCES, BUT WHY?
var hostile = new hostile(20,20);
var hostileA = new hostile(20,20);
I have hostile created and I have this instance being called in the update method, hostile.move() however the var hostile works, the var hostile does not, I have checked the code hostile is the only reference in the file.
var hostile = new hostile(20,20);
You just overwrote the hostile variable to refer to that instance rather than the constructor.
This is one of the reasons that constructors are UpperCamelCase by convention
You're erasing your constructor with
var hostile = new hostile(20,20);
Then you can't create other hostile objects.

How to create a bullet animation? (Shooter Game)

I am trying to make a shooter game, but I have got some troubles with bullet animation. Each time I click, a new bullet object created and animation starts, but after each click the created bullet disappears and same bullet starts over again which is faster than previous bullet. So I am trying to create new bullet after each click. A basic shooter game logic. Here is my code:
function newBullet(x,y,angle,speed,id,type) {
this.x = x;
this.y = y;
this.speed = speed;
this.angle = angle;
this.radians = this.angle * Math.PI / 180;
this.id = id;
this.type = type;
this.drawBullet = drawBullet;
this.moveBullet = moveBullet;
}
function moveBullet() {
this.x = this.x + Math.cos(this.radians) * this.speed ;
this.y = this.y + Math.sin(this.radians) * this.speed;
ctx.drawImage( bulletImg, this.x, this.y);
}
function drawBullet() {
bullet = new newBullet(playerX,playerY,getAngle(),2,1,1);
bullets[bullets.length] = bullet;
setInterval("bullets[bullets.length - 1].moveBullet()", 25);
}
canvas.addEventListener("mousedown",drawBullet,false);
Try adding var here:
var bullet = new newBullet(playerX,playerY,getAngle(),2,1,1);
If you want to add a bullet to an array you should use push. This will update bullets.length:
function drawBullet() {
var bullet = new newBullet(playerX,playerY,getAngle(),2,1,1);
bullets.push(bullet);
setInterval(bullets[bullets.length - 1].moveBullet, 25);
}
The reason your created bullet disappeared: you replaced bullets[0] each time. And the new bullet was faster then the old one because bullets[0].moveBullet was called n-times in each 25ms interval, where n is the number of bullets you "created".

Categories

Resources