JavaScript: Issues with methods and functions in refactored object - javascript

First time asking!
my refactored methods (methods used to be inside object) are not recognizing their relations to the object anymore... How do I get these to work?
I'm trying to apply a move and accelerate function to this object (car). The move_fn increases the car's position linearly (1, 2, 3, 4... n). The acc_fn increases the car's acceleration exponentially by adding the car's previous speed increase with its current position (30mph + 2 position = 32mph, 32mph + 3 position = 35mph, 35mph + 4 position = 39mph, etc.). Also, function_runner runs both methods simultaneously, which keeps everything commencing in order:
var move_fn = function(){
var prev_position = this.position
this.position += + 1
console.log(this.type + " is moving from " + prev_position + " to " +
this.position + '.')
}
var spd_fn = function(){
var prev_speed = this.speed
console.log(this.position)
this.speed += this.position
console.log(this.type + ' is accelerating from ' + prev_speed + ' to ' +
this.speed + '.' )
}
var function_runner = function(){
this.move_fn()
this.acc_fn()
}
var car = {
type: 'Honda CRV',
position: 1,
speed: 30,
move: move_fn,
speed: spd_fn,
fn_run: function_runner
}
car.function_runner()

Car no longer has a method called function_runner, you've assigned it to the fn_run method, so you'd call car.fn_run(). Same thing with move_fn - renamed to move, and "acc_fn" isn't defined anywhere.
So it'd be:
var move_fn = function(){
var prev_position = this.position
this.position += + 1
console.log(this.type + " is moving from " + prev_position + " to " +
this.position + '.')
}
var spd_fn = function(){
var prev_speed = this.speed
console.log(this.position)
this.speed += this.position
console.log(this.type + ' is accelerating from ' + prev_speed + ' to ' +
this.speed + '.' )
}
var function_runner = function(){
this.move()
this.speed()
}
var car = {
type: 'Honda CRV',
position: 1,
speed: 30,
move: move_fn,
speed: spd_fn,
fn_run: function_runner
}
car.fn_run()
...although it is a strange way of structuring it.

Related

How to calculate an Endpoint (E1.x E1.y) with Javascript where source, slope and distance are given?

I need to calculate an endpoint (E1.x and E1.y) with Javascript but I cannot get it to work properly.
Given are the starting point with S1.x and S1.y coordinates, the distance d and the coordinates of a target point (T1.x and T1.y). T1 determines the direction/line/slope S1-E1 (so E1 is on the line S1-T1, sometimes between S1-T1, sometimes not).
Needed is the calculated endpoint (E1.x and E1/y) that is on a line determined by S1-T1 with a distance d (calculated from S1).
S1.y is always lower than T1.y, but S1.x is sometimes positive/higher and sometimes negative/lower than T1.x.
function calculateEndPoint() {
console.log("pressedDistance: " + pressedDistance + " sourceCoordinates " + sourceCoordinates + " actualDist: " + actualDist + " targetCoordinates " + targetCoordinates + " difference : " + difference);
var S1 = {
x : sourceCoordinates[0],
y : sourceCoordinates[1],
};
var T1 = {
x : targetCoordinates[0],
y : targetCoordinates[1]
};
// slope
var slope = (T1.y-S1.y)/(T1.x-S1.x);
// Find angle of line
var theta = Math.atan(Math.abs(slope));
// the coordinates of the E1 Point
var E1x= Math.abs(T1.x + pressedDistance * Math.cos(theta));
var E1y= Math.abs(T1.y + pressedDistance * Math.sin(theta));
console.log("E1x: " + E1x);
console.log("E1y: " + E1y);
var calcCo = [E1x,E1y];
return calcCo;
}
The answer is illustrated and explained here: https://math.stackexchange.com/a/2109383
function calculateEndPoint() {
var x = sourceCoordinates[0] - (pressedDistance *(sourceCoordinates[0]-targetCoordinates[0]))/actualDist;
var y = sourceCoordinates[1] - (pressedDistance *(sourceCoordinates[1]-targetCoordinates[1]))/actualDist;
console.log("x: " + x + " y: " + y);
var calcCo = [x,y];
return calcCo;
}

Get position in javascript not working

I want to make a small game, but I have some start up problems.
When I try to get the position of track or trackCont, it always returns x: 0, y: 0. Doesn't get right position moving the DIV with:
float: right;
display: block;
and even doesn't work using:
position: absolute;
left: 100px;
Here's the code I am using:
var Player = new Array();
var trackEntity;
function getPosition(elem){
xPos = 0;
yPos = 0;
while(elem){
xPos += (elem.offsetLeft + elem.clientLeft);
yPos += (elem.offsetTop + elem.clientTop);
elem = elem.offsetParent;
}
return {x: xPos, y: yPos};
}
window.onload = function(){
trackEntity = document.getElementById("trackCont");
for (i = 0; i < 4; i += 1){
Player[i] = new Object();
document.body.innerHTML += "<div id='p" + i + "' class='player'></div>";
Player[i].entity = document.getElementById("p" + i);
Player[i].entity.style.backgroundColor = "rgb("
+ Math.floor(Math.random() * 256) + ", "
+ Math.floor(Math.random() * 256) + ", "
+ Math.floor(Math.random() * 256) +
")";
Player[i].entity.style.left = (getPosition(trackEntity).x) + 20;
Player[i].entity.style.top = (getPosition(trackEntity).y) + 20;
}
}
http://jsfiddle.net/dh8uf6Lp/
You need to supply a unit to when assigning a value to css left.
Player[i].entity.style.left = (getPosition(trackEntity).x) + 20 +"px";
If you assign a value to a css dimension or position property it will not update when no unit is given.
It seems that when getPosition(trackEntity) is called it doesn't know where it is in the DOM. This is caused by
document.body.innerHTML += "<div id='p" + i + "' class='player'></div>";
This causes the browser to redraw all elements and trackEntity loses it reference.
Solution: do not insert html via innerHTML, but create the div and append it to the DOM.
Player[i].entity = document.createElement("div");
Player[i].entity.id = "p" + i;
//etc.
document.body.appendChild(Player[i].entity);
//Run position code.
http://jsfiddle.net/dh8uf6Lp/3/

Edit a variable within an array

I'm attempting to create a Choose Your Own Adventure type of game, and I'm currently trying to write a 'battle' script. What I've got so far is:
var name = "Anon";
var health = 100;
var youAttack = [name + " hits the " + opp + " with his sword", name + " uses magic!", name + " is too scared to fight!"];
var youBattle = function() {
var youBattle = youAttack[Math.floor(Math.random() * 3)];
return youBattle;
};
var opp = "Orc";
var oppHealth = 100;
var oppAttack = ["The " + opp + " hits you with his hammer!", "The " + opp + " does nothing!", "The " + opp + " back hands you!"];
var oppBattle = function() {
var oppBattle = oppAttack[Math.floor(Math.random() * 3)];
return oppBattle;
};
oppBattle();
youBattle();
I've done it like this so the opponent and player names can easily be changed.
What I'm struggling to figure out is how I can add / remove health from both the opponent and the player depending what attack is used. Obviously no health would be removed if the opp / player does nothing.
Is there a way I can do this without a bunch of messy if / else statements?
I was hoping for something easy like name + " hits the " + opp + " with his sword" + health = health - 10; but obviously that didn't work.
Thanks in advance!
http://jsbin.com/qerud/3/edit
Hope this isn't too much code:
var Attack = function(hero,opp,damageReceived,damageGiven,message){
this.message = message;
this.damageGiven = damageGiven;
this.damageReceived = damageReceived;
this.opp = opp;
this.hero = hero;
this.attack = function(opp){
this.hero.health -= damageReceived;
this.opp.health -= damageGiven;
return this.message;
};
};
var Character = function(name,health){
this.name = name;
this.health = health;
};
hero = new Character('Anon',100);
orc = new Character('Orc',150);
attack1 = new Attack(hero,orc,5,0,"The " + orc.name + " back hands you!");
attack2 = new Attack(hero,orc,0,0,hero.name + " is too scared to fight!");
attack3 = new Attack(hero,orc,15,0,"The " + orc.name + " hits you with his hammer!");
attack4 = new Attack(hero,orc,0,25,hero.name + " uses magic!");
attacks = [attack1,attack2,attack3,attack4];
while(hero.health > 0 && orc.health > 0){
console.log(attacks[Math.floor(Math.random() * 4)].attack());
console.log('Hero Health: '+ hero.health);
console.log('Orc Health: '+ orc.health);
}
if(hero.health > 0 ){
console.log(hero.name + ' won');
} else {
console.log('The ' + orc.name + ' won');
}
I can tell you first hand that trying to write this type of code uses a lot of if/else and more statements, regardless of what language you're using. You can use an array to hold the values of your attack patterns:
var attackName = ["Punch", "Sword", "Magic"]
var attackDamage = [3, 5, 4]
function youAttack(ATK, PHit) {
if(playerHit) {
playerDamage = ATK + PHit;
oppHealth = oppHealth - playerDamage;
return oppHeath;
} else {
alert("You missed!");
}
}
But, without seeing exactly what you're doing I cannot say how you should do your attacks and damages. I can only assume. You will need a system of evaluating attacks, misses, etc. that does use IF/ELSE Statements at least somewhere.

multiply two properties inside an object

There are two properties for my bike method.front gear and rear gear.i want another property which will be a new property called gear ratio property which can be obtained by multiplying front and rear gear numbers.the code i have written giving continuous error.how it can be fixed.
function write() {
var bicycle = {
price: 20000,
model: "raleigh",
front_gear: 3,
rear_gear: 7,
gear_ratio: function () {
ratio: this.front_gear * this.rear_gear,
}
}
document.write("this is a " + bicycle.gear_ratio.ratio + " speed bike");
}
window.onload = write;
gear_ratio: function () {
return this.front_gear * this.rear_gear
}
document.write("this is a " + bicycle.gear_ratio() + " speed bike");
Is about the best I can recommend you do. If you still want an object:
gear_ratio: function () {
return {
ratio: this.front_gear * this.rear_gear
}
}
document.write("this is a " + bicycle.gear_ratio().ratio + " speed bike");
It is possible to write something like:
function bike(settings){
// Make settings an object so we can use it always
if (typeof settings != 'object')
settings = {}
// if settings has a price use that, otherwise use 0
this.price = settings.price || 500;
this.model = settings.model || "custom";
this.front_gear = settings.front_gear || 2;
this.rear_gear = settings.rear_gear || 2;
this.__defineGetter__("gear_ratio", function(){
return this.front_gear * this.rear_gear;
});
}
function write() {
var bike1 = new bike({
price: 20000,
model: "raleigh",
front_gear: 3,
rear_gear: 7,
});
var bike2 = new bike({
front_gear: 3,
});
document.write("<br /> bike 1 is a " + bike1.gear_ratio + " speed bike by " + bike1.model + " costing " + bike1.price);
document.write("<br /> bike 2 is a " + bike2.gear_ratio + " speed bike by " + bike2.model + " costing " + bike1.price);
}
Where the function call is implied, however this will require your bike to be an actual instantiated class, and won't work in every browser and is harder to debug. Let me know if you want a better explanation.
change this
window.onload = write;
to this
window.onload = write();
you're calling the function in an inappropriate way

Kinetic JS: Zoom an image and keep self build arrow (lines) at same position

Im trying to zoom an kinetic object(image) in and out (this works).
The problem is i also have an arrow (custom built consits of three lines).
So on the first step i move the arrow to a certain point of the image and when i hit the zoom in action, the image zooms (or sets its scale) corresponing to the zoom factor.
Problem: the tip of the arrow should stay on the same point as it was before the zoom action(on the image) but the arrow object itself shouldnt be zoomed.
Here is the code for my zoom action:
--//ZOOM IN
htp.p(q'! document.getElementById('P10005_ZOOM_IN').addEventListener('click', function() {
zoom_factor = document.getElementById('P10005_ZOOM_FACTOR').value;
console.log('zoom factor: ' +zoom_factor);
var scale = image.getScale();
console.log('scale: ' +scale);
console.log('whole ' + parseFloat(image.getScale().x)+parseFloat(zoom_factor));
//layer get x and y offset
var x;
var y;
var arrow_layer1 = stage.get('.ARROW');
arrow_layer1.each(function(arr) {
x = arr.getX();
y = arr.getY();
});
//arrow object
arrow_layer = stage.get('.arrow');
if(parseFloat(image.getScale().x)+parseFloat(zoom_factor) < 10)
{
console.log('image x before ' + image.getX());
x_coord = image.getX() + (image.getWidth()*image.getScale().x)/2;
y_coord = image.getY() + (image.getHeight()*image.getScale().y)/2;
var old_x = image.getX();
var old_y = image.getY();
var oldWidth = image.getWidth();
var oldHeigth = image.getHeight();
image.setScale((image.getScale().x)+parseFloat(zoom_factor),(image.getScale().y)+parseFloat(zoom_factor));
image.setPosition(
x_coord-image.getWidth()/2*image.getScale().x,
y_coord-image.getHeight()/2*image.getScale().y);
var x_pos;
var y_pos;
//inserting new arrow positions
arrow_layer.each(function(arr) {
console.log(arr);
console.log(arr.getPoints());
console.log(arr.getPoints()[3]);
console.log(x + ' ' + y);
var image_x = old_x;
var image_x_arrow = x;
var image_x_end = old_x+ oldWidth;
var image_y = old_y;
var image_y_arrow = y;
var image_y_end = old_y+oldHeigth;
console.log('x settings: ' + image_x + ' ' + image_x_arrow + ' ' + image_x_end);
console.log('y settings: ' + image_y + ' ' + image_y_arrow + ' ' + image_y_end);
var ratio = image_x_arrow-image_x;
console.log('x ratio: ' + ratio);
var rat = oldWidth/ratio;
console.log('x ratio: ' + rat);
var ratio_y = image_y_arrow-image_y;
var rat_y = oldHeigth/ratio_y;
var new_image_x = image.getX();
console.log('new x position: ' + new_image_x);
var new_image_x_end = image.getX() + image.getWidth()*image.getScale().x;
console.log('new image end: ' + new_image_x_end);
var new_image_y = image.getY();
var new_image_y_end = image.getY() + image.getHeight()*image.getScale().y;
var new_x = image.getWidth()*image.getScale().x/rat;
console.log('x len end: ' + new_x);
var new_y = image.getHeight()*image.getScale().y/rat_y;
x_pos = new_image_x+new_x;
// x_pos = new_image_x+ ratio*image.getScale().x;
console.log('new coordoinate: ' + x_pos);
y_pos = new_image_y+new_y;
// y_pos = new_image_y+ratio_y*image.getScale().y;
console.log(x_pos);
});
arrow_layer1.each(function(arr) {
arr.setX(x_pos);
arr.setY(y_pos);
});
document.getElementById('P10005_ZOOM_CURRENT').value = (image.getScale().x)*100;
stage.draw();
}
}, false); !');
Im trying to read the offset from the ARROW layer and store its variables.
Then .arrow will give me the arrow object.
I want to go with the relation of the distances from to "old" image and update it to the ztoomed image, but i think it doesn´t work
any suggestions?

Categories

Resources