Dynamically creating objects and clicking one of the objects - javascript

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/

Related

Best/easiest way to make a 2D Chess board using Javascript/HTML5?

I am building a web based chess game in Javascript. I'm using the HTML5 canvas to display the board by drawing rectangles.
I am trying to implement the move logic. So when a chess piece is clicked, and then they click on an empty block, I want to move it. However, it is quite tedious using the canvas. I need to do the following:
Update my 2D grid of objects to reflect the change, I set the current
square to undefined and set the new square to the object being moved
clearRect(..) which I still haven't got to work
Redraw the image at the new position
Is there a better way?
Also, how do I deal with the 'double click'. I currently using a boolean that holds if the piece was pressed, and if it was and they click on an empty square I call the move function. Are there any other ways of doing this? Additionally, are there any tools for making it seem like the chess piece is being dragged?
I appreciate any help. Thanks guys.
Over the years I've written a lot of chessboards for HTML. In the end the simplest approach I think is:
Keep an array (either 1d or 2d, both have pros and cons) with just piece names (e.g. "wp"=white pawn, "bn"=black night, "--" empty). Nothing to be gained with an OO-approach or even a generic piece object.
Use one single canvas for the board, drawing the pieces on them with drawImage.
Write a function that just draws everything and call it when needed (don't bother erasing/drawing single pieces).
For piece dragging empty the square and create a separate dragged div containing just the dragged piece (redrawing the full board during drag can be slow for low-end mobile devices).
For dragging attach move and up handlers to the document and not to the canvas, so that you won't miss up events when the mouse is outside of the browser window.
Start dragging on mousedown and attach events for mousemove and mouseup. This will work both on computers and on mobile phones without having to handle specific cases. Always call preventDefault and stopPropagation.
Make full-page view with no overflow and handle resize yourself (you'll need to add some mobile-specific metas to stop phones messing up with the page).
HTML can really do impressive things with just 2d canvas, as an example see this 2d/3d chessboard. One single file less than 300k (200k zipped).
Easiest you say?
Using chessboard.js has to be the easiest way and it is 2D.
HTML
<div id="board1" style="width: 400px"></div>
JavaScript
var board1 = ChessBoard('board1', 'start');
It has very good documentation and tons of different examples (customization) and can be downloaded here.
Learning by coding -- Good for you!
Here are a few tips to get you started:
A reusable structure for your game:
Create a JS object for each of your chess pieces and save those piece-objects in an array.
// an example piece object
var blackKing={
player:'black',
pieceType:'king',
image:blackKingImageObject,
currentSquare:['E','1'],
isCaptured: false,
// etc...
}
// a pieces-array
var pieces=[];
pieces.push(blackKing);
Create a function that does all of these things:
clearRect the entire canvas,
redraw the chess board,
use the piece-array to redraw all the pieces onto the chessboard.
About click vs double-click vs dragging:
Yes, that's troublesome and requires special handling.
Many coders handle it this way:
Listen for mousedown and save that timestamp and initial mouse position.
If a mouseup plus another mousedown occurs quickly it's a double-click.
If a mousemove of more than a few pixels occurs then it's the start of a drag.
Otherwise, it's a single-click.

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)

Display 2 cursors at the same time using Javascript

I'm actually working on a video conferencing project and I was wondering if there is any way to display 2 cursors at the same time based on mouses' position of the 2 guys talking to each other?
Basically, they gonna share the same screen, but I want one to be able to see the mouse pointer of the other one since they gonna work on common exercice.
Thanks for the help
Wouldn't it be easiest to have a div element with a custom mouse cursor that you move around in JavaScript by the coordinates received from the other user?
I think having two equal-looking cursors would just cause confusion.

How to detect collision with JS

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.

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