Javascript add function to object - javascript

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;
}
}

Related

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

Multiple instance of same object

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 ?

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);
}

Javascript set method

I have a javascript "class", which looks like that:
function MapObject(x, y, size){
var x = x;
var y = y;
var size = size;
var color = "red";
this.draw = function(g2d){
g2d.setFillColor(color);
g2d.fillRect(x, y, size, size);
}
this.setColor = function(newColor){
color = newColor;
}
this.collision = function(mousex, mousey){
return mousex > x && mousex < x + size && mousey > y && mousey < y + size;
}
}
My problem is, i want to name the paremeter in the "setColor" function "color", too.
I know this from java:
void setColor(Color color){ this.color = color; }
Is there a way to achieve this in javascript?
I already tried:
this.setColor = function(color){
this.color = color;
}
That does not work.
I dont get any error, but the value isnt changing..
If you want to keep your setup with local variables (i.e. var color) then no, you can't name the parameter color, since it shadows the outer variable.
You need to tell the function which color variable you're amending. In your sample, setColor creates a new private variable of that function, and assigns the value of newColor to it. You should prepend the this keyword to the assignment operator within the setColor() function:
this.setColor = function(color){
this.color = color;
}
jsFiddle Demo
You'll need to update your draw() function too, if you wish to use the object property:
this.draw = function(g2d){
g2d.setFillColor(this.color);
g2d.fillRect(this.x, this.y, this.size, this.size);
}

three.js lookat() function not works as i need

there is my code
http://codepen.io/usf/pen/pGscf
in this part
function animate() {
//sun.rotation.x = t/1000;
sun.rotation.y += 0.01;
t += 0.1;
earth.position.x = Math.sin((2*Math.PI/24*60*60)*timeScale*t)*300;
earth.position.z = Math.cos((2*Math.PI/24*60*60)*timeScale*t)*200;
camera.position.set(sun.position);
camera.lookAt(earth.position);
//sun.lookAt(earth.position);
renderer.clear();
renderer.render(scene, camera);
window.requestAnimationFrame(animate, renderer.domElement);
};
i want to look on earth from sun (lol), but i see nothing.
how can i fix that? I think there is some little mistake, but can't find it out
There is something wrong here: camera.position.set(sun.position);
The set method should be used like this :
set: function ( x, y, z ) {
this.x = x;
this.y = y;
this.z = z;
return this;
}
Use camera.position.copy(sun.position) instead.

Categories

Resources