How to redefine variable in Javascript

Started by
21 comments, last by DangerDoom 11 years, 1 month ago

I have a strange problem with javascript at the moment. I'm so much used to Java so I get very frustated when it doesn't work out in the same way. I have a function Jet that is a plane which I try to move. Then I have the x += dx; in my move-function as usual.

dx is 0 at the beginning. When I change it to 1 or 2 or something it works fine and my Jet moves, but I want to start with 0 and then I want to change dx to 1 when pressing the keyboard. That is no problem at all in Java, but this I don't understand. Nothing happens...

At the top I have

var jet1 = Jet();


function Jet()
{
   var x = 200;
   var y = 300;
   var dx = 0;
   var dy = 0;

   var Jet = function()
   {
   }
   Jet.prototype.draw = function(){
     jet1.update();
     ctxJet.drawImage(plane, x, y);
      
   }

 Jet.prototype.setDX = function(speed)
   {
       dx = speed;    
   }

   Jet.prototype.getX = function()
   {
      return x;
   }
   
   Jet.prototype.getY = function()
   {
      return y;
   }
   
   Jet.prototype.update = function(){
    ctxJet.clearRect(0, 0, 800, 600);
   }

   Jet.prototype.move = function()
   {
      x += dx;
      y += dy;
      return this;
   }
   return new Jet();
}

// And here is the keyboard which doesn't work (the keyboard input works, but not the variable change)

function checkKeyDown(e) {
    var keyID = e.keyCode || e.which;
    if (keyID === 38 ) { //up arrow     
        jet1.setDX = 1;
        jet1.dx = 1;    
    }
}

How am I supposed to solve this? I can't reach and change the variable.

Advertisement
Your variables, as written, belong to the Jet() function, not to the Jet object which it constructs and returns.

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]

Remove the top level function Jet().

function Jet()

{

// We're inside a function now

var Jet = function()

{

}

// the var jet ONLY exists within this function

}

Jet now means the top level function Jet() NOT your variable, you have no access to the Jet variable.

Dan Mayor

Professional Programmer & Hobbyist Game Developer

Seeking team for indie development opportunities, see my classifieds post

I tried to remove the top level but it stopped working. Maybe I have to change more things. Since I'm quite new to this it would be nice if you could give an example of how I shall fix this by using my existing code. That would be very nice!

Can it be an idea to use the "this"-word or something? I don't get that word exactly but I've seen it before. How shall i structure this code to make it work like above in the easiest way? I'm going to make a bullet "class" as well so I need to have values for every object in my bullet "class". Every bullet will have to have it's own dx value and so on so I don't think it works by making the variable global...or?

declare the variables the same way you declare the Jet functions, Jet.prototype.x as an example.

i'm no javascript programmer, but i would use json for this:


var Jet = function(){
     return {
           x: 0,
           y: 0,
           dx: 0,
           dy: 0,
           draw: function(){
               this.update();
               ctxJet.drawImage(plane, x, y);
            }
            ...
     };
};
 

also, AFAIK, there's no concept of private fields on javascript, so x, y, dx and dy will be accessible directly, with no need for get's and set's, but, again, i'm not a javascript programmer, i only use it for simple web stuff.

EDIT: just noticed this line:

jet1.setDX = 1;

didn't you mean jet1.setDX(1); ? what you are doing there is trying to overwrite setDX with the value 1, i doubt that this is what you want...

As Mito pointed out. Your bug is here:


function checkKeyDown(e) {
    var keyID = e.keyCode || e.which;
    if (keyID === 38 ) { //up arrow     
        jet1.setDX = 1;
        jet1.dx = 1;    
    }
}

jet1.setDX is a function, so you have to go jet1.setDX(1);

jet1.dx is "private", so you can't access it that way.

Since you start out with...

var jet1 = Jet();

then that means in following code there is potential bug, can you spot it?


   Jet.prototype.draw = function(){
     jet1.update();
     ctxJet.drawImage(plane, x, y);
      
   }

What if you create another jet with var jet2 = Jet();

Yes of course, it was a fatal and clumsy mistake to write setDX = 1. Of course it is supposed to be setDX(1);

That works just fine! Thanks for seeing that.

I have a new question and I can maybe use this thread for that question too.

I want to make my bullet array but I don't really get it. If it was Java, then I would have done:

ArrayList<Bullet> bullets = new ArrayList<Bullet>();

And then:

for(Bullet b : bullets){

drawImage(b.getImage(), b.getX(), b.getY());

b.move();

}

And then when pressing the fire button I would have done:

bullets.add(new Bullet(x,y));

I don't really get how to do this in JavaScript. My bullet code looks kind of exactly like my Jet code above here in this thread. Do you have an idea of how to do this in JavaScript?

something like:


var bullets = new Array();

for(b in bullets){
     drawImage(b.getImage(), b.getX(), b.getY());
     b.move();
}
 

to add a bullet:


bullets[bullets.length] = new Bullet(x,y);
 

Some concerns:

1. i heard somewhere that the for.. in loop is ineficient, you might want to use a plain for,

2. AFAIK arrays in javascript are dynamic, they can hold any data type, there's no fixed length and they can hold different data types.

3. a good resource for javascript: http://w3schools.com/js/default.asp

Thanks a lot for that information. I'm almost there, it's just something that goes wrong. When it creates the bullet then the game freezes. I'd better post my whole game code. Ignore everything except the bullet code. Can you see what's wrong? If you look at the comments I've made then you can see at the top that I somehow need that bullet variable that I've created. I don't know why. Can someone see the problem? I'm almost there so it should be something very small to fix which I can't see:



var canvasJet = document.getElementById('canvasJet');
var ctxJet = canvasJet.getContext('2d');
var canvasBg = document.getElementById('canvasBg');
var ctxBg = canvasBg.getContext('2d');
var canvasBullet = document.getElementById('canvasBullet');
var ctxBullet = canvasBullet.getContext('2d');

var jet1 = Jet();
//This bullet variable is not supposed to be there, but if I remove it then it doesn't work
var bullet = CreateBullet(200,200);
var bullets = new Array();
  

var requestAnimFrame =  window.requestAnimationFrame ||
                        window.webkitRequestAnimationFrame ||
                        window.mozRequestAnimationFrame ||
                        window.msRequestAnimationFrame ||
                        window.oRequestAnimationFrame;

var background = new Image();
background.src = 'images/background.png';
background.addEventListener('load', init, false);

var plane = new Image();
plane.src = 'images/PlaneLeft.gif';
plane.addEventListener('load', init, false);

var bulletImage = new Image();
bulletImage.src = 'images/Bullet.gif';
bulletImage.addEventListener('load', init, false);


// main functions
function init() {
     
    loop();
    document.addEventListener('keydown', checkKeyDown, false);
    document.addEventListener('keyup', checkKeyUp, false);
}

function loop() { 
       ctxBg.drawImage(background, 0, 0);
        jet1.draw();
        jet1.move();
        bullet.draw();
        requestAnimFrame(loop);   
}

function clearCtxBg() {
    ctxBg.clearRect(0, 0, 800, 600);
    
}
// end of main functions

// My jet code
function Jet()
{
  var x = 200;
  var y = 300 ;
  var dx = 0;
  var dy = 0 ;

   var Jet = function()
   {
  
   }

   Jet.prototype.draw = function(){
     jet1.update();
     ctxJet.drawImage(plane, x, y); 
      
   }

 Jet.prototype.setDX = function(speed)
   {
       dx = speed;
      
   }
Jet.prototype.setDY = function(speed)
   {
       dy = speed;   
   }

   Jet.prototype.getX = function()
   {
      return x;
   }
   
   Jet.prototype.getY = function()
   {
      return y;
   }
   
   Jet.prototype.update = function(){
      ctxJet.clearRect(0, 0, 800, 600);
   }

   Jet.prototype.move = function()
   {
      x += dx;
      y += dy;
      return this;
   }
   return new Jet();
}
// End of jet code

// My bullet code
function CreateBullet(startX, startY)
{
   var x = startX;
   var y = startY;

   var Bullet = function()
   {
   }

   Bullet.prototype.draw = function(){
     bullet.update();
          for(b in bullets){
                ctxBullet.drawImage(bulletImage, jet1.getX(), jet1.getY());
                 b.move(1,0);
           } 
   }

   Bullet.prototype.getX = function()
   {
      return x;
   }

   Bullet.prototype.update = function(){
      ctxBullet.clearRect(0, 0, 800, 600);
   }
   
   Bullet.prototype.getY = function()
   {
      return y;
   }
   
   Bullet.prototype.move = function(dx,dy)
   {
      x += dx;
      y += dy;
   }
   return new Bullet();
}
// End of bullet code

// Keyboard code
function checkKeyDown(e) {
    var keyID = e.keyCode || e.which;
    if (keyID === 38 ) { //up arrow      
       jet1.setDY(-1); 
    }
    if (keyID === 39 ) { //right arrow  
      jet1.setDX(1);
      bullets[bullets.length] = new CreateBullet(jet1.getX(),jet1.getY());
    }
    if (keyID === 40 ) { //down arrow   
        jet1.setDY(1);  
    }
    if (keyID === 37 ) { //left arrow 
       jet1.setDX(-1);
    }
    if (keyID === 87) { //W key
       
    }
}

function checkKeyUp(e) {
    var keyID = e.keyCode || e.which;
    if (keyID === 38 ) { //up arrow 
    jet1.setDY(0);
    }
    if (keyID === 39 ) { //right arrow 
    jet1.setDX(0);
    }
    if (keyID === 40 ) { //down arrow 
   jet1.setDY(0);
    }
    if (keyID === 37 ) { //left arrow 
 jet1.setDX(0);
    }
    if (keyID === 87) { //W key
       
    }
}

// end of keyboard code

This topic is closed to new replies.

Advertisement