Collision realisation with SAT (canvas, javascript) - javascript

So, I have this simple 2d train sim, and I already made a pretty nice SAT realisation, that works without errors (at least I have not stumbled upon any):
function calcCollision(self){
var dist = self.distanceCheck();
var possible = [], collision = [];
var myBox, otherBox, myMin, myMax, otherMin, otherMax, myBoxRecalc = [], otherBoxRecalc = [];
for (var i=0;i<trainCount;i++){
if (dist[i]!="SELF"&&dist[i]<=(dTrain+10)){
possible.push(i);
}
}
if (possible.length!==0){
myBox = self.box();
self.hit = false;
for (i=0;i<possible.length;i++){
otherBox = window["train_"+possible[i]].box();
//для self координат
for (var j=0;j<4;j++){
myBoxRecalc[j] = XYtoBoxCoordinates(self,myBox[j][0],myBox[j][1]);
otherBoxRecalc[j] = XYtoBoxCoordinates(self,otherBox[j][0],otherBox[j][1]);
}
//для self координат, проекция на X
myMin = myBoxRecalc[0][0];
myMax = myBoxRecalc[0][0];
otherMin = otherBoxRecalc[0][0];
otherMax = otherBoxRecalc[0][0];
for (j=0;j<4;j++){
if (myBoxRecalc[j][0]<myMin) myMin=myBoxRecalc[j][0];
if (myBoxRecalc[j][0]>myMax) myMax=myBoxRecalc[j][0];
if (otherBoxRecalc[j][0]<otherMin) otherMin=otherBoxRecalc[j][0];
if (otherBoxRecalc[j][0]>otherMax) otherMax=otherBoxRecalc[j][0];
}
//console.log(myMin + " " + myMax + " " + otherMin + " " + otherMax);
if (otherMax<myMin||otherMin>myMax) break;
//для self координат, проекция на Y
myMin = myBoxRecalc[0][1];
myMax = myBoxRecalc[0][1];
otherMin = otherBoxRecalc[0][1];
otherMax = otherBoxRecalc[0][1];
for (j=0;j<4;j++){
if (myBoxRecalc[j][1]<myMin) myMin=myBoxRecalc[j][1];
if (myBoxRecalc[j][1]>myMax) myMax=myBoxRecalc[j][1];
if (otherBoxRecalc[j][1]<otherMin) otherMin=otherBoxRecalc[j][1];
if (otherBoxRecalc[j][1]>otherMax) otherMax=otherBoxRecalc[j][1];
}
//console.log(myMin + " " + myMax + " " + otherMin + " " + otherMax);
if (otherMax<myMin||otherMin>myMax) break;
//для other координат
for (j=0;j<4;j++){
myBoxRecalc[j] = XYtoBoxCoordinates(window["train_"+possible[i]],myBox[j][0],myBox[j][1]);
otherBoxRecalc[j] = XYtoBoxCoordinates(window["train_"+possible[i]],otherBox[j][0],otherBox[j][1]);
}
//для other координат, проекция на X
myMin = myBoxRecalc[0][0];
myMax = myBoxRecalc[0][0];
otherMin = otherBoxRecalc[0][0];
otherMax = otherBoxRecalc[0][0];
for (j=0;j<4;j++){
if (myBoxRecalc[j][0]<myMin) myMin=myBoxRecalc[j][0];
if (myBoxRecalc[j][0]>myMax) myMax=myBoxRecalc[j][0];
if (otherBoxRecalc[j][0]<otherMin) otherMin=otherBoxRecalc[j][0];
if (otherBoxRecalc[j][0]>otherMax) otherMax=otherBoxRecalc[j][0];
}
//console.log(myMin + " " + myMax + " " + otherMin + " " + otherMax);
if (otherMax<myMin||otherMin>myMax) break;
//для other координат, проекция на Y
myMin = myBoxRecalc[0][1];
myMax = myBoxRecalc[0][1];
otherMin = otherBoxRecalc[0][1];
otherMax = otherBoxRecalc[0][1];
for (j=0;j<4;j++){
if (myBoxRecalc[j][1]<myMin) myMin=myBoxRecalc[j][1];
if (myBoxRecalc[j][1]>myMax) myMax=myBoxRecalc[j][1];
if (otherBoxRecalc[j][1]<otherMin) otherMin=otherBoxRecalc[j][1];
if (otherBoxRecalc[j][1]>otherMax) otherMax=otherBoxRecalc[j][1];
}
//console.log(myMin + " " + myMax + " " + otherMin + " " + otherMax);
if (otherMax<myMin||otherMin>myMax) break;
collision.push(possible[i]);
}
} else return false;
if (collision.length!==0){
self.hit = true;
return collision;
} else return false;
}
It detects possible collision objects for self and returns their ID's if there is a collision. As I already said, it works just fine. The problem appears after that, when i'm trying to create a reaction on the collision. I've been struggling over the algorithm for almost a week, and that's the best solution that I came up with:
function moveCollided(){
for (var i = 0; i < trainCount; i++) {
var banged = calcCollision(window["train_"+i]);
//console.log(banged);
if (window["train_"+i].hit){
window["train_"+i].speed -= (window["train_"+i].speed/3);
for (var j = 0; j < banged.length; j++) {
window["train_"+banged[j]].speed += calcSpeedIncrement(window["train_"+i],window["train_"+banged[j]]);
}
}
}
setTimeout(moveCollided, 15);
}
This function decreases the speed of the train, and adds some speed (calcSpeedIncrement(self,other)) to the train it crashed into. I'm getting a nice collision effect in the straight tracks, but if you keep pushing forward one train slides over the other. And another problem with the same "sliding over" is the collision when one of the trains is standing on the turn.
Does anyone have any ideas on how to solve these problems?

I would simple not try to re-invent the wheel and go for an existing solution. Have you looked at the very popular 2D-physics engine Box2D? Here is a nice implementation of it in JavaScript.

Related

javascript alert showing code insted of string

first and foremost i'm new to javascript and coding. second, i'm coding a book store project with javascript with an alert message that shows each customer's total factor. but the alert message shows the code of my function "printFactor" insted of the string that is made by this function. this is my code:
function Book(name, writer, date, price)
{
this.name = name;
this.writer = writer;
this.date = date;
this.price = price;
}
function Customer(name, gender, turn)
{
this.name = name;
this.gender = gender;
this.turn = turn;
this.numberOfBooks = 0;
this.totalSum = 0;
this.bookList = [new Book("-", "-", "-", 0)];
//Functions.
this.addBook = function (newBook) {
this.numberOfBooks++;
this.bookList.push(newBook);
};
this.printFactor = function () {
var message = "";
if (this.numberOfBooks === 0) {
message = "No Books Has Been Added to Book List!";
return (message);
}
else {
message = this.name + " " + this.gender + " Number of Books: " + this.numberOfBooks + " Customer's Turn: " + this.turn + "\nBooks:\n";
var i;
var newMessage;
for (i = bookList.length - 1; i > 0; i--) {
newMessage = bookList[i].name + " " + bookList[i].writer + " " + bookList[i].date + " " + bookList[i].price.toString() +"\n" ;
message += newMessage;
this.totalSum += bookList[i].price;
this.bookList.pop();
}
newMessage = "Total Sum: " + this.totalSum;
message += newMessage;
return (message);
}
};
}
var book = new Book("Faramarz Bio", "Faramarz Falsafi Nejad", "1377/04/29", 13000);
var faramarz = new Customer("faramarz", "Male", 3);
faramarz.addBook(book);
faramarz.addBook(book);
faramarz.addBook(book);
faramarz.addBook(book);
var m = faramarz.printFactor;
window.alert(m);
You need to invoke the function:
var m = faramarz.printFactor();
As is your variable m contains a reference to the function, but you need to call it to get the result.
var m = faramarz.printFactor();
window.alert(m);
You simply don't call your function, this should work.
var m = faramarz.printFactor()
Beside you reference an unexisting variable 'booklist', that should be "this.booklist"
for (i = this.bookList.length - 1; i > 0; i--) {
newMessage = this.bookList[i].name + " " + this.bookList[i].writer + " " + this.bookList[i].date + " " + this.bookList[i].price.toString() +"\n" ;
You need to actually call the function by adding () to the end, like this:
var m = faramarz.printFactor()

How can I keep this loop going until balance is zero?

I am new to Javascript and have figured how to make the first line log to the console, however, how can I continue the loop and display the results as the balance gets lower until the balance is zero? I appreciate any help with this. Thanks in advance.
function displayPayment() {
var year = 0;
var balance = 1500;
var interest = 0.015;
var minimum = 0.02;
var payNum = 0;
if (balance > 0) {
var newPayNum = payNum + 1;
var newYear = year + 1;
var interestPaid = balance * interest;
var newBalance = interestPaid + balance;
var minPay = newBalance * minimum;
var balanceOwe = newBalance - minPay;
return (" " + newYear + " " + balanceOwe + " " + newPayNum + "
" + interestPaid);
}
}
console.log(" Year " + " Balance " + " PaymentNum " + " InterestPaid \n");
console.log(displayPayment());
You can use either the do while loop or just a while loop. However your balance does not change during the process, so the loop will never exit.

Reversing my encrypt method

I created minor encrypt method to convert a small string based on distance between characters, but can't for the life of me figure out how to reverse it without knowing the distance between each character from the initial conversion. See image for example how it works imgur.com/Ine4sBo.png
I've already made the encrypt method here (Javascript):
var all = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.#-?").split('');
var position;
//var oKey = "P";
function encrypt() // Encrypt Fixed
{
var sEncode = ("HI-MOM").split('');
var oKey = "P";
for (var i = 0; i < sEncode.length; i++) {
if (all.indexOf(oKey) < all.indexOf(sEncode[i])) {
position = all.indexOf(sEncode[i]) - all.indexOf(oKey);
output.value += "oKey: " + oKey + " distance to sEncode[" + i + "]: " + sEncode[i] + " Count: " + position + " Final Char: " + all[position-1] + "\n";
oKey = sEncode[i];
}
else {
position = all.length - all.indexOf(oKey) + all.indexOf(sEncode[i]);
output.value += "oKey: " + oKey + " distance to sEncode[" + i + "]: " + sEncode[i] + " Count: " + position + " Final Char: " + all[position-1] + "\n";
oKey = sEncode[i];
}
}
}
However, it's the decrypt() method that's killing me.
From what I can tell, your encrypt function can be reduced to this:
var all = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.#-?").split('');
function encrypt(str)
{
var sEncode = str.split('');
var result = '';
var oKey = "P";
for(var i = 0; i < sEncode.length; i++)
{
result += all[(all.indexOf(sEncode[i]) - all.indexOf(oKey) + all.length - 1) % all.length];
oKey = sEncode[i];
}
return result;
}
(I got rid of the if clause by adding all.length either way, and removing it again with the remainder operator if necessary.)
From there, all you need to do is flip the operands (- all.indexOf(oKey) - 1 becomes + all.indexOf(oKey) + 1 (and since we have no more subtractions, adding all.length is no longer necessary)) and reverse the order (so oKey gets assigned the transformed value instead of the original one):
var all = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.#-?").split('');
function decrypt(str)
{
var sEncode = str.split('');
var result = '';
var oKey = "P";
for(var i = 0; i < sEncode.length; i++)
{
oKey = all[(all.indexOf(sEncode[i]) + all.indexOf(oKey) + 1) % all.length];
result += oKey;
}
return result;
}

Flipping Shape Over Axis in JS

Here is the link to what i'm trying to do. I want to flip the blue bars to face to opposite way on the male side then I will fill in the female side as normal. This will create a tornado chart. I've been working on this for hours and I cant figure it out. I'm using Raphael JS.
http://math.mercyhurst.edu/~cmihna/DataViz/Butterfly.html
Just finished up reviewing your website's source code. No need for transforms, or anything of the such. Just some simple math added to your graph generating for-loop.
Your Code below
ind = 0
for (var key in gender) { // loop over all possible gender
for ( var i = 0; i < people.length; i++ ) { // loop over people
if (people[i][key] != 0) {
var barmale = paper.rect((w+leftPadding-rightPadding)/2,topPadding + vs*0 + i*vs, people[i][key],vs)
barmale.attr({'fill': '#0000A0', 'stroke-width':1})
var barfemale = paper.rect((w+leftPadding-rightPadding)/2, topPadding + vs*0 + i*vs, people2[i][key],-vs)
barfemale.attr({'fill': '#FFC0CB', 'stroke-width':1})
barmale.scale(1,-1)
//var dp = paper.circle(leftPadding + ind*hs + 0.5*hs, topPadding + vs*0.5 + i*vs, people[i][key])
//dp.attr({ 'fill': colors[ind] })
barmale.id = people[i][key] + " " + gender[key] + " people in this age range"
barmale.hover(hoverStart, hoverEnd)
barfemale.id = people[i][key] + " " + gender[key] + " people in this age range"
barfemale.hover(hoverStart, hoverEnd)
}
}
ind++
My Code Below
ind = 0
for (var key in gender) { // loop over all possible gender
for ( var i = 0; i < people.length; i++ ) { // loop over people
if (people[i][key] != 0) {
var barmale = paper.rect((w+leftPadding-rightPadding)/2 - people[i][key],topPadding + vs*0 + i*vs, people[i][key],vs)
barmale.attr({'fill': '#0000A0', 'stroke-width':1})
var barfemale = paper.rect((w+leftPadding-rightPadding)/2, topPadding + vs*0 + i*vs, people2[i][key],vs)
barfemale.attr({'fill': '#FFC0CB', 'stroke-width':1})
barmale.scale(1,-1)
//var dp = paper.circle(leftPadding + ind*hs + 0.5*hs, topPadding + vs*0.5 + i*vs, people[i][key])
//dp.attr({ 'fill': colors[ind] })
barmale.id = people[i][key] + " " + gender[key] + " people in this age range"
barmale.hover(hoverStart, hoverEnd)
barfemale.id = people2[i][key] + " " + gender[key] + " people in this age range"
barfemale.hover(hoverStart, hoverEnd)
}
}
ind++
You can see that I am subtracting the value of the Males from the placement on the graph. This causes the offset to "flip". Then, I modified the code a bit more the bring the female graph into the picture and properly label it.
Please let me know if any questions.
Proof below

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.

Categories

Resources