HTML5/JavaScript 2.5D - Making the ground in its own plane - javascript

So, I'm really interested in starting an HTML5/JavaScript project that mimics this type of 2.5D style:
http://superflashbros.net/2009/02/22/blue-rabbits-climate-chaos/
I'm personally trying to stay away from third-party scripts, and just keeping the core of the code pure JavaScript. However, my knowledge of trig isn't the best, so what would be the most appropriate way to tackle this perspective? I'm essentially wanting a game made with 2D sprites, but the ground plane (and perhaps buildings, as in the flash game) is skewed to give it a 3D feel. I'm not wanting to make a "Mode 7" engine (ie. SNES games like Mario Kart), as from my understanding that draws the ground in sections.
Any advice or resources I should look into?

I only ask you to read more about this, and just so you know, I tried to do this one and I achieved a good result but I halted that project because of my new job.
Anyway, you can look into some game engines written in javascript for starters, here is the list of the well known game engines you might find interesting:
1- Three.Js
2- GameQuery (JQuery Plugin)
3- Isogenic engine
You can also check this blog post for more info 66+ Open Source JavaScript Game Engine for Serious Developers
Note:
I know that you like to code your own javascripts and trust me this is a very good habit, However my advice is to try at least one Javascript game engine (if you can try more than one it will be good) to see how different engines work and how they run under the hood, that my friend will inspire you as well as help you to understand these engines to even make your own engine (this is NOT impossible).
I am not saying that you should try as much as you possible (coz that will be obviously pointless) but I am telling you to make small (tiny if possible) games with the engine of choice, I mean to get an idea of how Javascript game engines work in 2D then move to 2.5D or even 3D using WebGL technology.

I checked your reference game out, and understand what you mean by "2.5D". From my understanding, the best way to tackle this problem is to create a pseudo third dimension by transforming the x,y coordinates of objects. You would have a function that does the transformation for you, and here is my best guess of an example.
// This function takes in a x- and y-coordinates of an object corner and returns the
// coordinates of the corresponding back corner of an object.
var transform = function(x,y) {
// The farther the character is from the object, the more skew there would be.
// Here "char" is your globally recognized game character. If it was not in the scope
// of the function you'd have to pass it as a parameter.
var skew = (char.x > x) ? (char.x - x) : (x - char.x);
var newx = (skew * 0.1); // obviously this would be variable depending on your liking
// If the object corner is not on the ground (y == 0) then subtract from it's value,
// otherwise add.
var newy = (y > 0) ? (y - 10) : (y + 10);
};
In my example 10 is the amount of distance units to change the y-coordinate by. This is how it appears your example game does it. Hope my input helps,
Reagan

Related

Moving object performance - ThreeJs

Context :
I'm working on a pretty simple THREE.JS project, and it is, I believe, optimized in a pretty good way.
I'm using a WebGLRenderer to display lot's of Bode plot extracted from an audio signal every 50ms. This is pretty cool, but obviously, the more Bode I display, the more laggy it is. In addition, Bodes are moving at constant speed, letting new ones some space to be displayed.
I'm now at a point where I implemented every "basic" optimization I found on Internet, and I managed to get a 30 fps constantly at about 10.000.000 lines displayed, with such a bad computer (nVidia GT 210 and Core i3 2100...).
Note also i'm not using any lights,reflections... Only basic lines =)
As it is a working project, i'm not allowed to show some screenshots/code, sorry ...
Current implementation :
I'm using an array to store all my Bodes, which are each displayed via a THREE.Line.
FYI, actually 2000 THREE.Line are used.
When a Bode has been displayed and moved for 40s, it is then deleted and the THREE.Line is re-used with another one. Note that to move these, I'm modifying THREE.Line.position property.
Note also that I already disabled my scene and object matrix autoUpdate, as I'm doing it manually. (Thx for pointing that Volune).
My Question :
Do the THREE.Line.position modification induces some heavy
calculations the renderer has already done ? Or is three.js aware that my object did not change and
avoid these ?
In other words, I'd like to know if rendering/updating the same object which was just translated is heavier in the rendering process than just leaving it alone, without updating his matrix etc...
Is there any sort of low-level optimization, either in ThreeJS about rendering the same objects many times ? Is this optimization cancelled when I move my object ?
If so, I've in mind an other way to do this : using only two big Mesh, which are folowing each other, but this induces merging/deleting parts of their geometries each frames... Might it be better ?
Thanks in advance.
I found in the sources (here and here) that the meshes matrices are updated each frame no matter the position changed or not.
This means that the position modification does not induce heavy calculation itself. This also means that a lot of matrices are updated and a lot of uniforms are sent to the GC each frame.
I would suggest trying your idea with one or two big meshes. This should reduce javascript computations internal to THREE.js, and the only big communications with the GC will be relative to the big buffers.
Also note that there exists a WebGL function bufferSubData (MSDN documentation) to update parts of a buffer, but it seems not yet usable in THREE.js

Drawing slice in cocos2d-js

I wrote a game with Phaser engine but sadly i didn't get any good performance even with cocoonjs. I tried to optimize it but i don't think i can optimize enough.
So i'm trying to switch to cocos2d-js. I tried some examples with cocos2d and it works well. I think i will get the performance i'm looking for. I just need to achieve two things. I tried to use methods in DrawNode class but i couldn't do it. I'm new to computer graphics.
Drawing a slice, Just like the drawSlice method from this gist
Writing text along an arc with the given radius and angle
Update: I'll need the expensive calculations done by native code. I have around 18 of this shape independently animating the radius by 75-200 pixels in 100ms with user input. The problem i faced in Phaser was this expensive calculations.
Update2: Right now i'm able to draw this with #Sebastian's help. It's still incomplete.
Update3: I got good performance with Phaser with a few hacks. Maybe i won't need this, though others might need it.
Slice:
Text:
that functionality isn't done yet in cocos2d-html5. The best solution I can offer you is this function I submitted a while ago. It's not ideal, but it should do the trick. I'll wrap this function in the neccesary boilerplate code later if you don't know what to do with it (I'm a few hours away from my home PC and I don't have the time to make a full example right now):
var drawSolidArc= function(center, radius, degreesFrom, degreesTo, segments){
if(degreesTo<degreesFrom){
var temp = degreesTo;
degreesTo = degreesFrom;
degreesFrom = temp;
}
var i;
for(i=degreesFrom; i<=degreesTo;i++){
cc.drawingUtil.drawCircle(center, radius, cc.DEGREES_TO_RADIANS(-i+90), segments, true);
}
};
Also, this code is for v2.2.2, and it should be migrated to use v2.2.3's (or v3) DrawNode. Sorry for the incomplete answer, but I hope it'll send you in the right direction for the moment.
As for writing curved text, I think this is the closest thing I know exists: https://github.com/supersuraccoon/CircleLabelTTFDemo-HTML5

Generating events for gesture-controlled websites

I am very happy that I got the opportunity to work on a website that is gesture-based.
I have a few inspiration for this: link
I visited lot of websites and googled it, Wikipedia and gitHub also didn't help much. There is not much information provided as these technologies are in nascent stages.
I think I will have to use some js for this project
gesture.js (our custom javascript code)
reveal.js (Frame work for slideshow)
My questions are how come gestures generate events, how does my JavaScript interact with my webcam? Do I have to use some API or algorithms?
I am not asking for code. I am just asking the mechanism, or some links providing vital info will do. I seriously believe that if the accuracy on this technology can be improved, this technology can do wonders in the near future.
To enable gestural interactions in a web app, you can use navigator.getUserMedia() to get video from your local webcam, periodically put video frame data into a canvas element and then analyse changes between frames.
There are several JavaScript gesture libraries and demos available (including a nice slide controller). For face/head tracking you can use libraries like headtrackr.js: example at simpl.info/headtrackr.
I'm playing a little bit with that at the moment so, from what I understood
the most basic technique is:
you request to use the user's webcam to take a video.
when permission is given, create a canvas in which to put the video.
you use a filter (black and white) on the video.
you put some control points in the canvas frame (a small area in where all the pixel colors in it are registered)
you start attaching a function for each frame (for the purpose of the explanation, I'll only demonstrate left-right gestures)
At each frame:
If the frame is the first (F0) continue
If not: we subtract the current frame's pixels (Fn) from the previous one
if there were no movement between Fn and F(n-1) all the pixels will be black
if there are, you will see the difference Delta = Fn - F(n-1) as white pixels
Then you can test your control points for which areas are light up and store them
( ** )x = DeltaN
Repeat the same operations until you have two or more Deltas variables and you subtract the control points DeltaN from the control points Delta(n-1) and you'll have a vector
( **)x = DeltaN
( ** )x = Delta(N-1)
( +2 )x = DeltaN - Delta(N-1)
You can now test if the vector is either positive or negative, or test if the values are superior to some value of your choosing
if positive on x and value > 5
and trigger an event, then listen to it:
$(document).trigger('MyPlugin/MoveLeft', values)
$(document).on('MyPlugin/MoveLeft', doSomething)
You can greatly improve the precision by caching the vectors or adding them and only trigger an event when the vector values becomes a sensible value.
You can also expect a shape on your first subtractions and try to map a "hand" or a "box"
and listen to the changes of the shape's coordinates, but remember the gestures are in 3D and the analysis is 2D so the same shape can change while moving.
Here's a more precise explanation. Hope my explanation helped.

Structuring an HTML5 Canvas/JS Game

I'm new to HTML5/Canvas/Game programming, but have been tinkering around with it after reading a couple of books. I THINK I have a fairly good idea of how things work out. This question asks several smaller questions, but in general is basically a "structural approach" question. I'm not expecting verbose responses, but hopefully small pointers here and there :) Here is a link to a non-scrolling, and currently rather boring Super Mario World.
Super Mario World Test
NOTE: Controls are Left/Right and Spacebar to jump. This is only setup for Firefox right now as I'm just learning.
Did I Do Something Wrong at This Point?
Currently I've just focused on how Mario runs and jumps, and think that I've gotten it down fairly okay. The coin box doesn't do anything and the background is just an image loaded in for looks. Here's my approach, please let me know if there is anything entirely wrong with this:
Allows Mario to jump by enacting on 2 Y velocities (Gravity and Jump variables)
Allows Mario to run by enacting on 1 velocity (Left or Right "Friction" + Acceleration)
Sprites are used and positioned according to keypress/keydown
I'm not sure if this is right, but I'm using a constructor function to build an object, then inside the main animation loop I'm calling the prototype.draw function for that object to update all variables and redraw the object.
I'm clearing the entire canvas each Frame
Should I be splitting this into more than just a draw function, like Mario.move()?
I've setup a GroundLevel and a JumpLevel variable to create 2 planes of gameplay. The JumpLevel is setup to allow for controlling how high Mario can jump on the fly. The 2 places would allow for the ground to rise like a hill - keeping the point at which Gravity overrules Mario's jumping force at the same distance from the ground.
For clarity sake, everything is separated into different JS files, but would obviously consolidate.
Moving Forward:
Now that I've finished setting up how Mario moves around (I think there are a couple other minor things I might do like mushroom up/down and shooting fireballs). I think I can figure that out, but I'm really lost when it comes to visualizing the following and how HTML5/Canvas can handle this easily:
Scrolling background (I've tried setting up Ground Tiles and using Screen Wrapping, but that seems to cause a lot of uneven issues since I was moving the tiles in the opposite direction. Unfortunately, since I'm trying to account for acceleration, this threw off the count and was causing gaps in the ground. I ditched this idea. Would a DIV beneath the canvas with a large background image be the best solution?
Enemies: Would I create enemies the same way and run a loop for collision detection on every enemy during each frame?
Background Boxes: I'm trying to allow Mario to stand on the boxes in the background, but am unsure how to approach this. I currently have boundaries setup for Mario to stay on the canvas, do I continue to expand these conditions to setup different boundaries based on the boxes? I can see that having several boxes on the screen and doing it this way would get kind of crazy, especially if I would be doing the same hit testing for enemies? I know I'm missing something here....
Level Movement: This is somewhat related. When the Right key is pressed, basically everything in the level needs to move to the left. Would I need to track out all positions of everything that could touch Mario (boxes for him to stand on and enemies for him to collide with) during every animation frame? This seems like it would get kind of inefficient?
Thanks to all! I'll keep this updated with results/solutions :)
Wow, okay. I really like your question because you've obviously done a lot of thinking on this, but partially because of that it's incredibly broad and conversational. You'd do better to find a forum to ask this question.
...That being said, I'm gonna answer the handful of points I'm qualified to, in no particular order. :)
Level Movement: That's a weird (read: inefficient) way to do it. I wouldn't do any calculations based on onscreen positions: track a canonical, camera-agnostic set of coordinates for everything in your level and update the visuals to match. This will stop you from running into weird niggling problems where framerate impacts what you can and can't walk through, or causing slower computers to let Mario run through enemies without being damaged sometimes. Tracking positions this way will incidentally fix a lot of your other problems.
You should absolutely be splitting this into multiple functions. Having movement code and rendering code in the same place is going to screw you, particularly by interacting malignantly with your update/refresh rate. It's going to essentially mean that every time the player does a tricky jump the game does more updates than usual which will make animation/hit detection/etc much less likely to be even.
Enemies: I'd suggest rolling this in with everything else. Do one hit-detection pass against everything, and if you hit something check to see what it was. You could try to optimize this by only checking any given entity against objects within 100 pixels of itself, but if you do it this way you'll need to run separate collision detection events for every enemy. Letting the enemies clip through each other would be computationally cheaper.
Edit: I'd like to clarify about my first point on 'level movement.' Essentially, what you don't want to do is move every entity onscreen every time the camera does, or to store all entity locations as offsets from the camera location (in which case you're still effectively having to move everything, every time the camera moves.)
Your ideal approach is to store your enemy, block, terrain locations with X/Y coordinates that are offset from the absolute top-left of the level (at the very beginning.) In order to render a frame, you'd do essentially this: (pseudocode because we're talking about a hypothetical level format!)
function GetVisible(x,width,level_entities_array) {
for (i = 0; i < count(level_array); i++){
if (level_entities_array[i][x] > x && level_entities_array[i][x] < x+width) {
visible_elements[] = level_entities_array[i][x];
}
}
return visible_elements;
}
Boom, you've got everything that should be inside the window. Now you subtract the camera's x offset from the entity's x location and ZAP, you've got its position on the canvas. Pose as a team, 'cause things just got real.
You'll note that I'm not bothering to cull on the Y axis. This can be rectified by extrapolation, which I'm guessing you can handle because you've made it this far. This will be necessary if you want to do any Mario-style vertical exploration.
Yes, I know my pseudocode looks like C# and JavaScript's unholy lovechild. I'm sorry, that's just how I roll at 11:30 at night. ;)

Create fireflies in Javascript?

I want to create some randomly flying objects in a Unity 3D game. You can imagine them like fireflies. Now there're some tasks to do with them, include:
They usually fly randomly (of course).
They can fly away or fly back in some conditions.
I have to write some Javascript to do these things, but I don't know how to do. Can you help me? Thank you very much!
EDIT: I think I'll need these functions:
function Fly()
{
//control the gameObject to fly randomly
}
function FlyAway()
{
}
function FlyBack()
{
}
I would suggest that you look at the canvas tag, but then it will not work on IE as I don't know if 3D effects will work on excanvas well.
This gives you a drawable surface to do your graphics.
You will probably need to write your own primitive functions for the graphics, but it is very doable.
EDIT: You will need to use object oriented javascript for each of your fireflies, which will help you to move each of them each frame.
If you show your attempt at drawing graphics you can get more help.
As much as I hate condoning the use of Flash, this really sounds like a Flash job.
However, if you insist on using JavaScript, I'd thumb through some Chrome Experiments for 3D examples (w/canvas): http://www.chromeexperiments.com/
I've done an abstraction library that may help here:
DP_PanelManager
The library makes moving objects pretty simple - at the bottom of the page there's an example called "Useless Animation" - it's basically a checkerboard where each square randomly moves, changes size and changes opacity.
Something like that with fewer panels and a little math to do smoother travel (something like this should be easy enough to modify) should get you close.
The component also has simplified functions for collision detection and distance between panels (with bearing - the function will tell you how far apart two panels are AND in which direction they lay).
Hopes this gives you a headstart.
My approach would be
randomly create a x/y equation (may be from a given set, if you don't know how to 100% randomize this).
Decide, randomly if you go by the x or by the y.
decide the number of steps you take on the axis you chose in step 2.
move your element according to the x/y you get from the equation in step 1.
When you finished to move all the steps (number of steps is given in step 3), go back to step 1. In a loop.

Categories

Resources