Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am making a small game with basic physics and I can't figure out how to make circles interact with each other, and with rectangles. All I want is to make a solid object in the game. I can't use a engine or library, any ideas?
Have you see the tutorials on MSDN? In particular, the Detecting collisions in a 2D HTML5 game seems relevant to your interests.
In particular, here's the code used to detect collisions in that tutorial:
var circlesOverlap = function(circleA, circleB) { // Public. Returns true if the SVG circles A and B overlap, false otherwise.
var deltaX = circleA.cx.baseVal.value - circleB.cx.baseVal.value;
var deltaY = circleA.cy.baseVal.value - circleB.cy.baseVal.value;
var distance = Math.sqrt( (deltaX*deltaX) + (deltaY*deltaY) ); // The classic distance-between-two-points formula.
var radiusA = circleA.r.baseVal.value; // The radius of circle A.
var radiusB = circleB.r.baseVal.value; // The radius of circle B.
if (circleA.id == circleB.id) // If true, circleA and circleB are the same circle.
return false;
return distance <= (radiusA + radiusB);
}; // circlesOverlap()
that.circlesOverlap = circlesOverlap;
Note that the technique used in the tutorial is basically:
Track each object
Calculate the distance between the objects
Respond accordingly (e.g. when the distance is zero).
(Update: added the sample that seems most relevant to your question, per the comments below)
Do take time to read the full tutorial, though, for the full context and to ensure that due credit is duly credited.
Hope this helps...
-- Lance
Use an object to save each circle's x and y coordinates, x and y velocity (in pixels), as well as radius. keep a list of all of your circles. On each iteration of your animation loop, check that each circle's x and y coordinates plus or minus the radius are not on top of one another if the circles advance the number of pixels noted by their x and y velocities. If they are, handle what you want them to do (i.e. change direction, stop, etc.) and then redraw.
Related
This question already has answers here:
How to check if line segment intersects a rectangle?
(3 answers)
Closed 5 years ago.
I'm currently programming my first game in JavaScript, and I've never technically learned JavaScript, I'm more fluent with Python.
Anyway, I need to find a way to make a list of all the pixels between two points on a straight horizontal line. I would then use the list to reference whether the user's character is touching any of the pixels to trigger a screen change.
It would be something like
pixels = []
(Function here to add the pixels to the list)
For pixel in pixels
If (dist(object.x, object.y, pixel.x, 0) < 1) {
object.x = start point on new screen
Object.y =
Does this make any sense? I'm sorry I'm bad at explaining things but I could use the help.
You almost certainly don't want to test intersection this way. This is going to require many more steps than just doing standard line-rectangle collision detection.
I recommend googling something like "line rectangle intersection" or "line rectangle collision detection" for a ton of results, including:
line-rectangle collision detection
How to check if line segment intersects a rectangle?
How to find the intersection point between a line and a rectangle?
Line intersection with AABB Rectangle?
How to test if a line segment intersects an axis-aligned rectange in 2D?
https://gamedev.stackexchange.com/questions/111100/intersection-of-a-line-and-a-rectangle
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 6 years ago.
Improve this question
I'm trying to understand the math behind the Math.tan method but it doesn't make any sense. Can someone please explain to me how it works?
Firstly the mathematical formula to solve for a tangent angle is Tangent = Opposite/Adjacent. Which means I need to know two sides of the triangle to figure out the tangent angle. However the Math.tan method only accept a single argument in radians, not the length of two sides, so I don't understand how it's figuring out the angle of the tangent.
Next in examples they show passing impossibly huge radian values into the method and getting back a value. For example, W3 schools shows the example of Math.tan(90) but 90 radians equals 5,156.6 degrees which is an impossible angle for a corner of a right triangle.
How does this method work, what's happening behind the scenes that turns 90 radians into a tangent angle of -1.995200412208242
First let's talk about what a tangent is: Tangent is y/x for the coordinate at a specific point (see this YouTube video for an example).
So if you want the tangent of pi over 2, on a graph, that's at a 90 degree angle, so the coordinate is (0, 1). Then you just divide 1/0.
However, Math.tan isn't very precise. In Chrome 52, Math.tan(Math.PI / 2) (from the video above) is 16331239353195370, even though it should evaluate to the Infinity value in JavaScript (the mathematical value is actually undefined since it works out to 1/0).
According to this answer, the V8 implementation is:
function MathTan(x) {
return MathSin(x) / MathCos(x);
}
(As a side note: The value that Chrome actually outputs is larger than Number.MAX_SAFE_INTEGER, which you can prove by running Number.MAX_SAFE_INTEGER < Math.tan(Math.PI / 2) // => true, so Chrome takes it to be "close to infinity".)
Edit
The reason for the lack of a precise value is that pi is generally represented as a fixed value (since we have limitations in computer memory), even though it should be "Infinity" or "undefined" outside of the context of programming. For example, in my browser, Math.PI is fixed at 3.141592653589793.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am creating a game using JavaScript and the canvas API. I would like to implement a score at the top of the canvas which is constructed from a set of sprites on a sprite sheet. I have a sprite sheet containing images of numbers from 0 - 9. I want to know how I would go about displaying the player's current score to the canvas from the set of images. This would be including digits beyond 9(which I think confuses me most). Could you please annotate every line of code here just so I can fully understand.Thank you to everyone who replies.
Here is a quick simple solution using object property names to lookup the image details for each character you want to draw.
Convert the score to a string and then find the character code for each character in the string. Use the character code to look up the image details and then draw the image.
var numbers = { // for each character create a property that has its ASCII code
c48:{
image:imgForZero, // the image for the character zero
offx:0, // x offset if needed
offy:0, // y offset if needed
widthToNext: 10, // distance to the next character so you can have
// variable spacing
},
c49: ... // do the same for each character you want to display
// you can find the codes here
// http://www.w3schools.com/html/html_charset.asp
},
c50: ...
.. and so on
}
var chars = score.toString(); // turn score to a string
var x = 10,y = 20; // the top left of the score position
for(var i = 0; i < chars.length; i++){ // for each character
var charCode = chars.charCodeAt(i); // get the character code
var charData = numbers["c"+charCode]; // get the image details
if(charData !== undefined){ // make sure it is in the data
// draw the image with the offset
ctx.drawImage(charData.image, x + charData.offx, y + charData.offy);
// move to the next character position
x += charData.widthToNext; //
}
}
// All done
I answers to try and stop this getting a negative rating as it is a good question and shows how to use bracket notation to do lookups rather than array.find
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
How to create SVG / canvas sketches with comic style / hand jitter using Javascript
I am aware of the xkcd style JS plotter and of this article.
Note that I am not asking for plots, but for any kind of sketching, lines, shapes, text and so on.
What further methods / technologies exist using JS?
EDIT: After having thought and read some time about this I decided to implement my own JS library providing cartoon style drawing for SVG and HTML5 canvas.
It is called comic.js and can be found here.
I would be using a Canvas library to do that, just for the sake of simplicity when it comes to manipulating shapes.
The ones I would look for are Paper.js and Fabric.js.
However, I will focus on Paper.js because it is the one I worked with.
You can draw beziers or lines to create the shapes. You can even
import SVG's if you want. You can even have predefined shapes
such as Circles/Squares etc.
So you have the shapes, now what?
You can flatten them(subdivide them into segments, adding more
vertices to their geometry). You can increase the subdivision
interval which would result in high number of vertices/nodes per
path. Subdivision interval is the parameter maxDistance of the
flatten function.
Then you can walk along the vertices of each path/shape and move each
one by a certain degree(e.g 1-2 pixels to a random direction), by using position.x and position.y
If this is what you mean:
, then here is the code :
//STEP 1 -- create shapes, a circle and rectangle in this example
var myCircle = new Path.Circle(new Point(100, 70), 50);
myCircle.strokeColor = 'white';
myCircle.strokeWidth = 2;
var mySquare = new Rectangle(new Point(350, 250), new Point(190, 100));
var square = new Path.Rectangle(mySquare);
square.strokeColor = 'white';
square.strokeWidth = 2;
//STEP 2 -- Subdivide the shapes into segments. Parameter here is the max distance we walk along-the-path before adding a new vertex
myCircle.flatten(5);
square.flatten(4);
//STEP 3 -- Loop through the segment points of the path and move each to a random value between 1 and 4
for (var i = 0; i < myCircle.segments.length; i++) { //loop for circle
myCircle.segments[i].point.x += getRandomInt(1,3);
myCircle.segments[i].point.y += getRandomInt(1,3);
};
for (var i = 0; i < square.segments.length; i++){ //loop for square
square.segments[i].point.x += getRandomInt(1,3);
square.segments[i].point.y += getRandomInt(1,3);
};
//draw the paper view
view.draw();
//Utility function that returns a random integer within a range
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
and this is the jsFiddle for it:
The issue with this scenario is that each 'point' on your canvas is an object and the high number of points/nodes/vertices is a bit heavy for the browser to handle. So this might be an obstacle if your designs are complex and/or you want to have the user interact with your drawings(the interaction might prove sluggish).
Alternatively you can use plain-old canvas to do this, without any libraries but I wouldn't do that since I smell the need for algorithms to draw the shapes manually, then introduce jitter in those algorithms. This would be much faster, in terms of computation time, but it would be harder to implement since Canvas is a low-level kind of thing - it only remembers pixels drawed on and you would need to roll-your-own data structures to remember the shapes, their positions etc etc..
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I'm creating a single player web RPG in JavaScript.
It will not be too heavy of an events-based game, but I will be loading lots of objects to the screen.
I have two questions:
1st: I've used createJS to load my bitmaps, but noticed severe lag when I loaded several objects to the screen at once and animated them. I'm wondering if there is a better library than createJS to load objects.
2nd: I was planning on using PHP for user profiles, stats, etc... but found writing AJAX calls to the server required several steps...
first, send javascript variable to php using jquery .get()
then update database
then send newly updated variable back by using json_encode, and echoing out the variable.
Finally, store that updated variable back in a javascript variable
I'm wondering how something like this is handled in NodeJS. I read How to decide when to use Node.js? to figure out the usage of NodeJS, and this sentence in particular, "I believe Node.js is best suited for real-time applications: online games, collaboration tools, chat rooms, or anything where what one user does with the application needs to be seen by other users immediately, without a page refresh." spoke to me... but I'm still not sure if I'll need to use NodeJS instead of PHP.
Thank you
EDIT:
Hi, I think I'm doing the tiling and caching incorrectly...
In my Game.php, I call several function to create/draw the objects.
Game.php:
function init() {
canvas = document.getElementById("demoCanvas");
start();
}
function start() {
stage = new createjs.Stage("demoCanvas");
stage.mouseMoveOutside = true;
//Create Objects
createWorld();
createTiles();
createPlayers();
In my function tick() I have a centerViewTo which centers the player in the viewport relative to the background (mimicking a camera).
The issue with this is, I pass in a single bitmap bgBMP that I was drawing the player relative to. If I do tiling, I'm not sure how I can draw the player relative to the background image.
centerViewTo(stage.canvas, stage, segment, {x:0, y:0, width:bgBMP.image.width, height:bgBMP.image.height});
Moreover, http://www.createjs.com/Docs/EaselJS/classes/DisplayObject.html#method_cache says I should cache each object before adding it to the container? Anyway, I get why you add all objects to the stage and then cache the stage all at once.
So I've tried that here... but it's not rendering anything:
CreateObjects.js:
var world;
var bgBMP;
var tile;
var mapWidth = 10; //Map size is 1000... so 10x10 tiles
var mapHeight = 10;
//World will be a container to hold all objects
function createWorld() {
world = new createjs.Container();
bgBMP = new createjs.Bitmap("images/bg2.png");
world.cache(0, 0, mapWidth , mapHeight );
world.addChild(bgBMP);
stage.addChild(world);
}
function createTiles() {
for (var x = 0; x < mapWidth; x++){
for (var y = 0; y < mapHeight; y++){
var tile = new createjs.Bitmap('images/myTile.png');
tile.x = x * 32;
tile.y = y * 32;
world.cache(0, 0, mapWidth , mapHeight );
world.addChild(tile);
}
}
}
I'm currently creating a RPG too with createjs, and I can display 200 characters, with their own animations and life, without lag issues.
Createjs is a really good framework, but you have to understand how it works to avoid performance issues. It's very important to separe layers in differents containers, and to cache them. For example, if the background of your game is composed with a lot of 32x32 tiles (like in RPG maker), you should cache it since it's not supposed to change during the game.
For example :
var backgroundContainer = new createjs.Container();
// mapWidth and mapHeight is the number of X and Y tiles
for (var x = 0; x < mapWidth; x++){
for (var y = 0; y < mapHeight; y++){
var tile = new createjs.Bitmap('mytile-'+i+'.png');
tile.x = x * 32;
tile.y = y * 32;
backgroundContainer.addChild(tile);
}
}
backgroundContainer.cache(0, 0, mapWidth, mapHeight);
stage.addChild(backgroundContainer);
When you cache a container, it will draw all the children in a hidden canvas, and then just draw the cached canvas on your current canvas on stage update.
If you don't cache it, just think that every time you call stage.update(), all your children will be drawn one per one on your canvas.
About NodeJS : nodeJS is really cool with the Socket.IO plugin, which use the full power of web sockets. Forget ajax if you need real time for a game : websocket is what you need. Try socket.io http://socket.io/ you will love it ;)
EDIT:
You don't use the cache well, I think you need to understand first what exactly does the cache. In my previous example, you can see we add all tiles in a container. So we have mapWidth * mapHeight tiles. Every time you call stage.update(), it will loop each tile bitmap and draw it on canvas. So if you have a 50x20 map, it will draw 1000 bitmaps every stage.update(), that's not good for performances.
If we cache backgroundContainer all tiles will be draw on an internal canvas, and when stage.update() is called it will only draw 1 image this time instead of 1000. You have to cache your world container after you add all the tiles, as in my example.
The power of createjs is that you can encapsulate your display objects as you want, this is how I organize my containers in my game :
stage
screen
scene
background -> Here I display a background image (E.g: the sky)
body
tiles -> All my background tiles (I cache this)
events -> Map events (moving NPC, my character, etc.)
overlay -> Here I display an overlay image (E.g: a fog image with 0.2 opacity)
transition -> Here I make transition when my character go to a new map
When my character move on the map, I just need to move the body container (changing X and Y properties)