How to detect collision with JS - javascript

I'm making my first game in canvas+javascript, simple space shooter. The problem is that I use two nested for loops to check if rocket hits the enemy like this:
if((enemies[i][1]>rocket_posy&&enemies[i][1]<rocket_posy+40)&&enemies[i]0]>rocket_posx&&enemies[i][0]<rocket_posx+12))
and this causes small but still annoying lag. I was researching this here and on google but nobody seems to bother with that since we have different engines for this. Does anybody know how do solve this problem without nested for loops?
Thanks for answer!

You could either use a multidimensional array of "tiles" or a hash table where the key is the x and y position. On a "collision" in the data structure, you trigger your event for your collision.

Related

Avoiding certain coordinates in javascript

I have a 10x10 grid filled with objects in certain coordinates and I have a character that needs to get from the start to finish but I would like to avoid the certain coordinates on the route to the finish. Could someone please tell what would be the best way of approaching this in Javascript.
Also, if I was to initialise an array with the obstacles in an array how would I best code this to avoid those certain plots.
Thank you.
Sounds like you're looking for a pathfinding algorithm. The only one that comes to mind is A-Star, or "A*". The short version is that it recursively picks a random "next node" from the nodes it hasn't checked, being more likely to pick nodes that are physically closer to the goal. This is a commonly-used function that you may want to find a tutorial for (it doesn't have to be a JavaScript tutorial as long as you can reuse the concepts in JavaScript)

Better practice: Multiple objects into an array or separate threads?

I am working on a really, really simple rendition of the parachute shooter game, all in javascript.I am pretty new to javascript, with a background in java and OOP. Maybe I'm completely wrong here and maybe I just don't have any understanding of how javascript works, but the way I see it, I have two options to track the falling parachuters.
I can either create multiple parachuter objects and store them in some array of size n, however many can exist on the game field at one time or I can somehow create multiple threads of the parachuter object within the game board that will act independently of each other and only interact with the rockets being fired at them.
I'm not very familiar with the second option and don't really know how that would be achieved. I'm open to any pointers and different ideas for how to handle all of the parachuters. Which of those two is more efficient and manageable? Are both of them feasible? I don't necessarily want someone to give me their code for those (though it would be helpful), I just want to talk about theory and method.
Thanks for any help in advance.

Best approach for collision detection with HTML5 and JavaScript?

I'm trying to make a little platform game with pure HTML5 and JavaScript. No frameworks.
So in order to make my character jump on top of enemies and floors/walls etc., it needs some proper collision detection algorithms.
Since I'm not usually into doing this. I really have no clue on how to approach the problem.
Should I do a re-check in every frame (it runs in 30 FPS) for all obstacles in the Canvas and see if it collides with my player, or is there a better and faster way to do so?
I even thought of making dynamic maps. So the width, height, x- and y coordinates of the obstacle are stored in an object. Would that make it faster to check if it's colliding with the player?
1. Should I re-check in every frame (it runs on 30 FPS)?
Who says it runs in 30 FPS? I found no such thing in the HTML5 specification. Closest you'll get to have anything to say about the framerate at all is to programmatically call setInterval or the newish, more preferred, requestAnimationFrame function.
However, back to the story. You should always look for collisions as much as you can. Usually, writing games on other platforms where one have a greater ability to measure CPU load, this could be one of those things you might find favorable to scale back some if the CPU has a hard time to follow suit. In JavaScript though, you're out of luck trying to implement advanced solutions like this one.
I don't think there's a shortcut here. The computer has no way of knowing what collided, how, when- and where, if you don't make that computation yourself. And yes, this is usually, if not at all times even, done just before each new frame is painted.
2. A dynamic map?
If by "map" you mean an array-like object or multidimensional array that maps coordinates to objects, then the short answer has to be no. But please do have an array of all objects on the scene. The width, height and coordinates of the object should be stored in variables in the object. Leaking these things would quickly become a burden; rendering the code complex and introduce bugs (please see separation of concerns and cohesion).
Do note that I just said "array of all objects on the scene" =) There is a subtle but most important point in this quote:
Whenever you walk through objects to determine their position and whether they have collided with someone or not. Also have a look at your viewport boundaries and determine whether the object are still "on the scene" or not. For instance, if you have a space craft simulator of some kind and a star just passed the player's viewport from one side to the other and then of the screen, and there is no way for the star to return and become visible again, then there is no reason for the star to be left behind in the system any more. He should be deleted and removed. He should definitely not be stored in an array and become part of a future collision detection with the player's avatar! Such things could dramatically slow down your game.
Bonus: Collision quick tips
Divide the screen into parts. There is no reason for you to look for a collision between two objects if one of them are on left side of the screen, and the other one is on the right side. You could split up the screen into more logical units than just left and right too.
Always strive to have a cheap computation made first. We kind of already did that in the last tip. But even if you now know that two objects just might be in collision with each other, draw two logical squares around your objects. For instance, say you have two 2D airplanes, then there is no reason for you to first look if some part of their wings collide. Draw a square around each airplane, effectively capturing their largest width and their largest height. If these two squares do not overlap, then just like in the last tip, you know they cannot be in collision with each other. But, if your first-phase cheap computation hinted that they might be in collision, pass those two airplanes to another more expensive computation to really look into the matter a bit more.
I am still working on something i wanted to make lots of divs and make them act on physics. I will share somethings that weren't obvious to me at first.
Detect collisions in data first. I was reading the x and y of boxes on screen then checking against other divs. After a week it occurred to me how stupid this was. I mean first i would assign a new value to div, then read it from div. Accessing divs is expensive. Think dom as a rendering stage.
Use webworkers if possible easy.
Use canvas if possible.
And if possible make elements carry a list of elements they should be checked against for collision.(this would be helpful in only certain cases).
I learned that interactive collisions are way more expensive. Because you have to check for changes in environment while in normal interaction you simulate what is going to happen in future, and therefore your animation would be more fluid and more cpu available.
i made something very very early stage just for fun: http://www.lastnoob.com/

Dynamically creating objects and clicking one of the objects

I asked another version of this question on the gamedev.SE site earlier today but figured I could get better answers here. Also reformulated the question some. I hope this is okay couldn't find anything prohibiting it in the FAQ
I'm playing around with making a puzzle game, haven't done that much before I run into my first problem.
Question a) Basically, I want to create a certain amount of the same object/function (a ball). But the objects will be created dynamically (since the amount of balls could range from 3 to 25), preferably with a for loop pushing the different balls to an array.
However I'm not experienced enough to figure out a good way to do this.
Also, once I have my array of balls on the canvas, I want to be able to select one of the balls.
Question b) How do I know/determine which ball in the array was clicked?
Is a simple for loop enough and accessing the objects with [i]?
I made a jsFiddle example of what I want with 1 ball (you need to click the orange ball to select, then you can move it around by clicking anywhere on the canvas).
This is what I want to do, but with more balls, and the amount of balls is not specified (deciding the amount part i got covered). How could I solve this in a easy way?
Help appreciated.
Using a for loop is fine for your object generation.
As for detecting when you click an object in the canvas, this tutorial might help. It appears there is no built-in feature for tracking objects in your canvas - you simply do manual hit detection based on the common pixels under your mouse and object
Hope that helps
Paper.js has great DOM model, and out of the box ability to click and select items
http://paperjs.org/tutorials/project-items/transforming-items/
hit testing:
http://paperjs.org/examples/hit-testing/

Create a smooth curve from a series of GPS coordinates

I have looked at a lot of Q/A here on SO regarding similar (if not the same) question I have. Yet none had an answer I was able to understand.
I wish to input a series of GPS coordinates, and create a smooth curve that connects them all, and passes through ALL of them. Javascript is my preferred language and I have found this page
http://jsdraw2d.jsfiction.com/demo/curvesbezier.htm
It allows you to plot any number of points and when clicking the 'Draw Curve' button it does exactly what I want (except it is on html5 canvas whereas I want to use lat/lon values)
You can download the jsDraw2D source code here:
http://jsdraw2d.jsfiction.com/download.htm
The function in question is drawCurve() and it appears to calculate the points of the curve, creating a separate 'div' for each point as it goes along, while also appending them to the html page. I am presuming I need to get rid of the code for creating the html divs and instead add each point as it is calculated to an array or string. However, it is simply over my head (perhaps because it seems overwhelming and my understanding is not quite spot on).
I would post the code here, but it is pretty long, plus I am not sure how many other functions it calls/requires from the rest of the script.
The only other thing I can think of that needs to be considered is the +/- values in GPS coordinates. I am hoping that altitude changes would not effect the smooth line created too much, especially since it seems to create the new points so close together.
Any help in modifying that code would be greatly appreciated. If someone has some other approach, I am open to suggestions - however I would prefer a way that passes through ALL the input points (unlike some mathematical curve functions that do not)
Thanks!

Categories