Can I create an AI in JavaScript? - javascript

I want to create a game like Pong, and I want to know that if it is possible to create an AI (computer opponent) in JavaScript to control the right side. Pretend I have functions moveUp() and moveDown() for controlling the right paddles. So it is possible? Or will I have to use some kind of library?

Of course it is possible, a simple approach would just be to have the enemy attempt to follow the ball's current position on the y-axis. If the ball is lower than the center of the paddle, lower the paddle, etc...
There are a lot of other great frameworks that help in game creation, but learning and designing ones on your own from scratch is the best way.

Yes it very much is possible.
You may wish to start with a very simple AI: have the right paddle moveUp at a constant velocity, then moveDown when it hits the top, then repeat.
After you have that coded, you should be able to modify your AI routines to switch directions based on the y-component of the ball's velocity. Then you can modify the velocity of the paddle based on the x-component the ball's velocity.
After that, look at updating the paddle controls to move when they make contact the ball, w.r.t. the left paddles position (ie if the left paddle is ontop, attempt to hit the ball towards the bottom).

the math is simple enough but the platform is hardly the most efficient and it would of course depend on your degree of accuracy - the hard part would be the graphical aspect and for that it would make sense to use something simple like jquery animate or similar to manage the to and fro of the represented paddle(s) and ball

Related

Collision detection of 3d objects in p5.js

I am working on a infinite runner game, where 3d objects are involved - A rover and some obstacles, that move on a terrain. The game is made using p5.js WebGL functionality. I have almost completed the game, but the game should end when the rover hits any obstacle. I just want to know if I can detect the collision of both the 3d objects(the rover is a plane, and the obstacle is custom loaded model) and end the game...Simply, I want to know whether collision detection in WebGL is feasible, and if so how?
Please help me out on the same.
Thank you.
Ideally, indeed, you'd post a minimal sketch of your attempt at detecting the collision: something to make it easier for other to contribute (without making to many wild guesses on your behalf).
One idea is to check if the bounding box of the 3d model (defined by it's minX, minY, minZ, maxX, maxY, maxZ values) intersects with the plane (or the bounding box of the plane if it's simpler to keep things consistent). It won't be 100% accurate, depending on the loaded model (we don't even know what that is is), but it's a decent initial step.
For more accuracy a convex hull would be handy. If computing that from scratch in p5.js might prove difficult, perhaps you could use the same 3D editor to export the model to also generate a convex hull of the original model and export that to be used as simpler collision mesh.
Additionally, even through more advanced, you can look into using a physics engine such as ammo.js to handle the heavy collision math (and more) for you. (checkout the vehicle demo).

Should I use ctx.translate for an endless game-map?

Well, just imagine you keep going up but your player stays put in the middle, and as you go up the map generates itself randomly.
With the help of:
ctx.translate(0, 1);
the map moves towards you as you move up.
now, I have a few methods in mind and of them is ctx.translate, but I have a few questions:
1) in the long run, what I fear is that it will keep the memory of the previous drawings once they go out of the canvas borders and eventually the ctx x/y system will go to numbers as high as millions.
2)I need something which is CPU friendly. I am just not sure what ctx.translate does under the hood exactly, does it behave in the likes of ctx.clearRect and then redraws everything?
3) anything better to achieve the same thing will be lovely, I already know about the old clearRect(which is heavy) and redraw method, just looking for other options.
EDIT: the player may change his X coordinate in some position too.

Position resizable circles near each other

I am working on this browser-based experiment where i am given N specific circles (let's say they have a unique picture in them) and need to position them together, leaving as little space between them as possible. It doesn't have to be arranged in a circle, but they should be "clustered" together.
The circle sizes are customizable and a user will be able to change the sizes by dragging a javascript slider, changing some circles' sizes (for example, in 10% of the slider the circle 4 will have radius of 20px, circle 2 10px, circle 5 stays the same, etc...). As you may have already guessed, i will try to "transition" the resizing-repositioning smoothly when the slider is being moved.
The approach i have tried tried so far: instead of manually trying to position them i've tried to use a physics engine-
The idea:
place some kind of gravitational pull in the center of the screen
use a physics engine to take care of the balls collision
during the "drag the time" slider event i would just set different
ball sizes and let the engine take care of the rest
For this task i have used "box2Dweb". i placed a gravitational pull to the center of the screen, however, it took a really long time until the balls were placed in the center and they floated around. Then i put a small static piece of ball in the center so they would hit it and then stop. It looked like this:
The results were a bit better, but the circles still moved for some time before they went static. Even after playing around with variables like the ball friction and different gravitational pulls, the whole thing just floated around and felt very "wobbly", while i wanted the balls move only when i drag the time slider (when they change sizes). Plus, box2d doesn't allow to change the sizes of the objects and i would have to hack my way for a workaround.
So, the box2d approach made me realize that maybe to leave a physics engine to handle this isn't the best solution for the problem. Or maybe i have to include some other force i haven't thought of. I have found this similar question to mine on StackOverflow. However, the very important difference is that it just generates some n unspecific circles "at once" and doesn't allow for additional specific ball size and position manipulation.
I am really stuck now, does anyone have any ideas how to approach this problem?
update: it's been almost a year now and i totally forgot about this thread. what i did in the end is to stick to the physics model and reset forces/stop in almost idle conditions. the result can be seen here http://stateofwealth.net/
the triangles you see are inside those circles. the remaining lines are connected via "delaunay triangulation algorithm"
I recall seeing a d3.js demo that is very similar to what you're describing. It's written by Mike Bostock himself: http://bl.ocks.org/mbostock/1747543
It uses quadtrees for fast collision detection and uses a force based graph, which are both d3.js utilities.
In the tick function, you should be able to add a .attr("r", function(d) { return d.radius; }) which will update the radius each tick for when you change the nodes data. Just for starters you can set it to return random and the circles should jitter around like crazy.
(Not a comment because it wouldn't fit)
I'm impressed that you've brought in Box2D to help with the heavy-lifting, but it's true that unfortunately it is probably not well-suited to your requirements, as Box2D is at its best when you are after simulating rigid objects and their collision dynamics.
I think if you really consider what it is that you need, it isn't quite so much a rigid body dynamics problem at all. You actually want none of the complexity of box2d as all of your geometry consists of spheres (which I assure you are vastly simpler to model than arbitrary convex polygons, which is what IMO Box2D's complexity arises from), and like you mention, Box2D's inability to smoothly change the geometric parameters isn't helping as it will bog down the browser with unnecessary geometry allocations and deallocations and fail to apply any sort of smooth animation.
What you are probably looking for is an algorithm or method to evolve the positions of a set of coordinates (each with a radius that is also potentially changing) so that they stay separated by their radii and also minimize their distance to the center position. If this has to be smooth, you can't just apply the minimal solution every time, as you may get "warping" as the optimal configuration might shift dramatically at particular points along your slider's movement. Suffice it to say there is a lot of tweaking for you to do, but not really anything scarier than what one must contend with inside of Box2D.
How important is it that your circles do not overlap? I think you should just do a simple iterative "solver" that first tries to bring the circles toward their target (center of screen?), and then tries to separate them based on radii.
I believe if you try to come up with a simplified mathematical model for the motion that you want, it will be better than trying to get Box2D to do it. Box2D is magical, but it's only good at what it's good at.
At least for me, seems like the easiest solution is to first set up the circles in a cluster. So first set the largest circle in the center, put the second circle next to the first one. For the third one you can just put it next to the first circle, and then move it along the edge until it hits the second circle.
All the other circles can follow the same method: place it next to an arbitrary circle, and move it along the edge until it is touching, but not intersecting, another circle. Note that this won't make it the most efficient clustering, but it works. After that, when you expand, say, circle 1, you'd move all the adjacent circles outward, and shift them around to re-cluster.

How to detect if a shape hits another in html5 canvas?

I'm trying to build a motorbike game in html5 canvas with javascript.
Right now I have a wheel and a simple gravity which increases the position from the top of the canvas until the wheel hits the bottom of the canvas. When I start the game, the wheel just drops to the bottom of the canvas.
I want to create a curved ground for the wheel to ride on. The problem is that I don't know how to calculate if the wheel hits this ground.
Here is a illustration. I want the wheel to drop until it hits the curved ground, and if I'm moving the wheel, it needs to follow the shape's edge.
image http://i.minus.com/iFvy1dbnouvy6.png
I don't want to use any libraries or engines, only javascript and html5. Do you have any ideas or solutions?
Similar to the other answer, you can simply have an if statement that says
if tire.y < line(tire.x) then tire.y = line(tire.x) - 1
the line function can just be an array or some formula that will contain the y value of the line when given any x-value.
In order to detect when the wheel hits the ground, you should have the coordinates of the ground boundary (e.g.: a polyline) and the wheel's ray and center position.
You detect collision by checking that your wheel y coordinate (cener + ray) is below the y coordinate of your polyline at certain x(s). You should segment your polyline in a resonable way, by carefully selecting your endpoints.
Probably there are other ways to accomplish this task, but this is the first which I came out.
Here is the solution which you're looking for Collision Detection (elastic)..
.--------------------------------------------------------------------------------------------.
Here's a simple & Good tutorial for learning physics especially for Game Developers

RaphaelJS - Simultaneous Animation

I have pong balls that are being generated very consistently, but the
rates change dynamically. So in a given second, there could be 1 pong
ball that's being drawn and translating across the screen (constantly
from left to right), or 50.
I have a pong paddle that responds based on the generation of these
balls, and it's supposed to "catch" every one of the balls that's
being sent towards its destination. The x coordinate is always the
same, because the pong paddle never moves, but the y coordinate is
randomly generated.
Here's an extremely similar (if not identical) example of what I'm
doing: http://www.youtube.com/watch?v=HeWfkPeDQbY
I have a lot of this code already written, but I'm afraid my design
for catching the balls is incorrect/inefficient. It works, but the
paddle very easily becomes out of sync with the balls that are being
thrown towards it.
The way I'm currently doing this is by putting each ball object into a
global array, and the paddle pops the next ball off of this queue and
uses basic arithmetic to calculate the speed at which it needs to
translate to the y coordinate of the next ball.
Is there a more efficient way of doing this?
I'll assume the issue is that the motion of each ball (and the paddle) is controlled by a separate timer. Since there are no guarantees about the exactness of js timers, there are really no guarantees about how many, many timers will interact.
Two broad approaches to correct the problem are:
Instead of using raphaeljs animation primitives, implement a synchronous animation yourself with setTimer, updating the position of each ball (and the paddle) in sync. Then any timer-stutters apply consistently across all elements in your universe.
Use feedback to course-correct the paddle position, e.g. by having a special setTimer that periodically looks at how close the paddle is to where it needs to be, and if necessary calls .stop() on the paddle's animation in order to re-execute with more aggressive parameters, closing the gap.

Categories

Resources