Why cocos2d-js + chipmunk, only works with web build - javascript

I've implemented simple example based on this
My example uses chipmunk along with cocos2d-js.
The problem is that physic only works with web builds. With the other builds (native ones - ios, mac, win32) all object are shown but they just hang - no animation.
My update method is called with specified intervals, where I execute "step" method on space object.
All my sprites are loaded using PhysicSprite class.
PS: I'm using cocos2d-js v3.0alpha

Use this tutorial:
http://www.cocos2d-x.org/docs/tutorial/framework/html5/parkour-game-with-javascript-v3.0/chapter6/en
I tried it both in the browser and in the iphone simulator and it worked just fine.

you should apply impulse on your physics body, they will move surely but if you would try to move the body with schedular by changing its coordinate on every call they will work on web but not on native ones like iOS or mac .
for example:-
var mass = 1;
var width = 1, height = 1;
playerBody = new cp.Body(mass , cp.momentForBox(mass, width, height));
playerBody.applyImpulse(cp.v(200, 300), cp.v(0, 0));// now you can move your playerBody
it will work well on all the platform but if you try my alternate solution
ie:-
init: function{
var mass = 1;
var width = 1, height = 1;
this.playerBody = new cp.Body(mass , cp.momentForBox(mass, width, height));
this.schedule(this.move);
},
move: function(dt){
this.playerBody.getPos().x += 2 * dt;
this.playerBody.getPos().y += 2 * dt;
}
this will work on web but on native platform like iOS or mac it will not move the playerBody at all. i don't know the reason yet if i got one i will let you know

Related

Get the pixel screen size in Spark AR studio (for Facebook)

I am starting to work with Spark AR studio and I looking for to get the screen size in pixel to compare the coordinate obtained by the gesture.location on Tap.
TouchGestures.onTap().subscribe((gesture) => {
// ! The location is always specified in the screen coordinates
Diagnostics.log(`Screen touch in pixel = { x:${gesture.location.x}, y: ${gesture.location.y} }`);
// ????
});
The gesture.location is in pixel (screen coordinate) and would like to compare it with the screen size to determine which side of the screen is touched.
Maybe using the Camera.focalPlane could be a good idea...
Update
I tried two new things to have the screen size:
const CameraInfo = require('CameraInfo');
Diagnostics.log(CameraInfo.previewSize.height.pinLastValue());
const focalPlane = Scene.root.find('Camera').focalPlane;
Diagnostics.log(focalPlane.height.pinLastValue());
But both return 0
This answer might be a bit late but it might be a nice addition for people looking for a solution where the values can easily be used in script, I came across this code(not mine, forgot to save a link):
var screen_height = 0;
Scene.root.find('screenCanvas').bounds.height.monitor({fireOnInitialValue: true}).subscribe(function (height) {
screen_height = height.newValue;
});
var screen_width = 0;
Scene.root.find('screenCanvas').bounds.width.monitor({fireOnInitialValue: true}).subscribe(function (width) {
screen_width = width.newValue;
});
This worked well for me since I couldn't figure out how to use Diagnostics.log with the data instead of Diagnostics.watch.
Finally,
Using the Device Info in the Patch Editor and passing these to the script works!
First, add a variable "to script" in the editor:
Then, create that in patch editor:
And you can grab that with this script:
const Patches = require('Patches');
const screenSize = Patches.getPoint2DValue('screenSize');
My mistake was to use Diagnostic.log() to check if my variable worked well.
Instead use Diagnostic.watch():
Diagnostic.watch('screenSize.x', screenSize.x);
Diagnostic.watch('screenSize.y', screenSize.y);
Screen size is available via the Device Info patch output, after dragging it to patch editor from the Scene section.
Now in the open beta (as of this post) you can drag Device from the scene sidebar into the patch editor to get a patch that outputs screen size, screen scale, and safe area inserts as well as the self Object.
The Device patch
The device size can be used in scripts using CameraInfo.previewSize.width and CameraInfo.previewSize.height respectively. For instance, if you wanted to get 2d points representing the min/max points on the screen, this'd do the trick.
const CameraInfo = require('CameraInfo')
const Reactive = require('Reactive')
const min = Reactive.point2d(
Reactive.val(0),
Reactive.val(0)
)
const max = Reactive.point2d(
CameraInfo.previewSize.width,
CameraInfo.previewSize.height
)
(The point I want to emphasize being that CameraInfo.previewSize.width and CameraInfo.previewSize.height are ScalarSignals, not number literals.)
Edit: Here's a link to the documentation: https://sparkar.facebook.com/ar-studio/learn/documentation/reference/classes/camerainfomodule

Phaser 3: destroying all instances of a sprite

So i'm trying to make my game unload a bunch of un-used resources. It's proving to be a lot more complicated. here's my code:
var meteor = this.physics.add.group();
this.physics.add.collider(meteor, sput, deathControl, null, this);
meteorSpawnFrequency = 500;
setInterval(spawnMeteor, meteorSpawnFrequency);
var meteorCap = 0;
function spawnMeteor() {
//Create Meteors
meteorCap++;
meteors = meteor.create(Math.floor(Math.random() *800) + 1, 30, "meteor");
//Edit Meteors
meteors.depth = -1;
meteors.setVelocityY(500);
meteors.setScale(Math.floor(Math.random() * 2) + 1);
meteors.setCollideWorldBounds(true);
//Destroy meteors after the cap reaches 10
if(meteorCap > 10){
meteors.destroy();
console.log("meteors destroyed");
meteorCap = 0;
}
}
I'm using an interval to spawn the sprites, and all of it works just fine. What I'm trying to do is set a cap that when 100 meteors are present, they'll get destroyed, and the cap gets set back to 0, to repeat this process.
Only problem is it's not working. How do I get this working?
Almost certainly a scope issue and there isn't enough source code shown to determine the root cause. But meteorCap looks dangerous like a local variable, so reading it from spawnMeteor isn't going to work.
Also, don't use setInterval, there is literally a TimerEvents feature built into the Phaser API for exactly this that is game-step safe and manages the scope context for you. Here is one such an example.

Continuous animation with Angular JS and Snap SVG

I'm trying to get smooth continuous animation using AngularJS and Snap SVG. I thought I'd solved the problem; my animations run smoothly for several hours. But I left my solution running over the weekend in Chrome, Opera, Safari and Firefox (Internet Explorer cannot run it at all). When I came into work this morning Firefox and Opera had both crashed, and the pages on Chrome and Safari had both frozen.
My animation functions are as follows:
/* the centre of the hub in this drawing */
var hubCentre = "269, 367";
/* the time to complete an animation move */
var moveTime = 100;
/* the Angular module name I'm defining */
var turbineApp = angular.module('spinningTurbine', []);
/* the controller for that module */
turbineApp.controller('turbineController', ['$scope', function ($scope) {
$scope.speed = 0;
$scope.angle = 0;
$scope.height = 150;
/**
* rotate the element with the specified tag about the hub centre location
* to indicate the specified value.
*/
$scope.sweep = function( tag, angle) {
var elt = Snap(tag);
var directive = "r" + angle + ", " + hubCentre;
elt.animate({
transform: directive
}, moveTime);
}
function spinner() {
setTimeout( function() {
$scope.angle += parseFloat($scope.speed);
$scope.sweep( '#blades', $scope.angle);
spinner();
}, moveTime);
}
spinner();
}]);
My question is, does the JavaScript setTimeout() function consume resources (e.g. stack)? Or is Snap SVG consuming resources e.g. by continuously extending the transformation path?
Ideally I want this animation to run indefinitely, so I need either to work out what is causing the browsers to crash or else recode it using a different mechanism. Does Angular JS have other mechanisms for performing a non-terminating loop?
Would a better option be to use $interval()
$interval(function() {
... Do Cool Stuff Here
}, moveTime);
You will need to inject it into your controller..

KeyDown/KeyUp 70-120ms delay. How to reduce?

We're developing arcade (a lot of action and speed) browser 2d-game using canvas.
Sometimes our testing players report us that there is a delay: player still moving 5-10 pixels away after keyup.
I've digged this issue, you can see yourself delay http://jsfiddle.net/C4ev3/7/ (try keydown/up any key as fast as you can). My results is from 70 to 120ms. And i think that's a lot. (FYI, our network latency is 10-20ms).
Any ideas how to reduce this delay?
upd i've noticed that on good hardware this delay is under 30-40ms. But i'm testing on core2duo, winxp, chrome 19 - it's not a P4 with IE6 :)
Hi one thing you could do is instead of using an anonymous function try using defined functions,
http://jsfiddle.net/C4ev3/10/ - for me this reported at 50-100 MS
However i would not recommend jQuery for Canvas Applications it's very big for the very little you using, you should try using native Javascript
http://jsfiddle.net/C4ev3/11/ - for me this reported 30-70 MS
Javascript Threading
One thing i noticed in the comments Javascript is not Multi-Threaded Well Urm-Arr,
it sort of is setInterval is Async not Sync, however affecting the window is a single thread E.G if you have a Class that has some number is it using a setInteval will use another thread and not have a problem altering the math however in the Task then requires a Draw on the page it will enter the bottom of the JS handle Que,
Certain parts of Javascript are on a different thread how ever any thing changing the page has to run on the Main Thread same as any Windows application if your thread want to change the Form your have to invoke the main thread to do it for you
however it is not multi-threaded like any thing else you cant just handle or abort at a given Wim like windows,
Other ASync Tasks include AJAX has the option to be both Async and Sync
Updated to show my comment about FPS limiting:
Please bear with me. This is linking to a project that is allready built to show the example:
so my Game is Completely OOP
var elem = document.getElementById('myCanvas');
var context = elem.getContext("2d");
context.fillStyle = '#888';
context.lineWidth = 4;
// Draw some rectangles.
context.fillRect(0, 0, 800, 600);
context.fillStyle = '#f00';
var ball = new Ball();
var leftPadel = new Padel(10, 60, 40, 120);
var rightPadel = new Padel(750, 520, 40, 120);
pong = new Pong();
pong.draw();
setTimeout("ball.move()", pong.redrawTime());
Inside my pong class is where all the main workings of the game goes but here are the FPS bit you need to see
this.fps = 30;
this.maxFPS = 60;
this.redrawTime = function(){
return (1000 / this.fps)
}
this.lastDraw = (new Date)*1 - 1;
Then as you can see my Interval is on ball.move this calls the main pong class again on redraw at the End of the redraw i have the FPS checking and limiting code
this.fps = ((now=new Date) - this.lastDraw);
if(this.fps > this.maxFPS){
this.fps = this.maxFPS;
}
this.lastDraw = (new Date)*1 - 1;
if(this.reporting = true){
console.clear();
console.log("FPS: "+this.fps.toFixed(1))
}
setTimeout("ball.move()", pong.redrawTime());
This then forces you to get the Best Possible FPS without queuing the Main Thread
Try this:
e.stopPropagation()
Stops the bubbling of an event to parent elements, preventing any
parent handlers from being notified of the event.
e.preventDefault()
Prevents the browser from executing the default action. Use the method
isDefaultPrevented to know whether this method was ever called (on
that event object).
My min. results in Google chrome: 7ms

HTML5 Game (Canvas) - UI Techniques?

I'm in the process of building a JavaScript / HTML5 game (using Canvas) for mobile (Android / iPhone/ WebOS) with PhoneGap. I'm currently trying to design out how the UI and playing board should be built and how they should interact but I'm not sure what the best solution is. Here's what I can think of -
Build the UI right into the canvas using things like drawImage and fillText
Build parts of the UI outside of the canvas using regular DOM objects and then float a div over the canvas when UI elements need to overlap the playing board canvas.
Are there any other possible techniques I can use for building the game UI that I haven't thought of? Also, which of these would be considered the "standard" way (I know HTML5 games are not very popular so there probably isn't a "standard" way yet)? And finally, which way would YOU recommend / use?
Many thanks in advance!
EDIT
I've moved this question over to gamedev.stackoverflow.com. You can find the new question here: https://gamedev.stackexchange.com/questions/7090/html5-game-canvas-ui-techniques/7115#7115
You can do it a million ways. However you feel most comfortable and your engineers feel most confident.
If you're looking for inspiration or a code example, here's one way that I do it. I have a function that repeatedly draws a menu until a button is pressed. When the button is pressed, the game loads and the old menu click event listeners are removed and new game click event listeners are added. I also end the old draw loop of the menu and start a new game draw loop. Here's some selected snippets to give you the idea of how its done:
Game.prototype.loadMenu = function() {
var game = this;
var can = this.canvas;
// now we can use the mouse for the menu
can.addEventListener('click', game.menuClickEvent, false);
can.addEventListener('touchstart', game.menuClickEvent, false);
// draw menu
this.loop = setInterval(function() { game.drawMenu() }, 30);
};
Game.prototype.drawMenu = function() {
// ... draw the menu
}
Game.prototype.loadLevel = function(levelstring) {
// unload menu
var can = this.canvas;
var game = this;
can.removeEventListener('click', game.menuClickEvent, false);
can.removeEventListener('touchstart', game.menuClickEvent, false);
if (this.loop) clearInterval(this.loop);
// ... other level init stuff
// now we can press keys for the game
//can.addEventListener('click', game.gameClickEvent, false);
can.addEventListener('touchstart', game.gameClickEvent, false);
can.addEventListener('keydown', game.gameKeyDownEvent, false);
this.loop = setInterval(function() { game.tick() }, 30);
}
// called from tick()
Game.prototype.draw = function(advanceFrame) {
// ...
}
This way I'm able to separate out game drawing and game events from menu drawing and menu events. It also gives me leeway to use game/animation elements in my menus should I want to make them look real pretty.
(I posted this at the twin gamedev discussion too)
I do not think that there is a "standard" for this. It highly depends on your UI. I think using the DOM elements is better in most cases, since you do not need to build all of the UI components, events, etc. yourself. They can be styled with CSS to achieve the desired look. If this is not enough, you'll probably need to build the interface elements yourself, but you should make sure that this is really needed. It is probably a huge amount of work to roll your own solution.
Try this :
With Visual js you can setup page like this :
Visual-JS multiplatform game engine windows GUI - source editor
OnPage editor - for design
You will get :
*99% canvas 2d
Add new object
Create webcam component (nui or normal)
Create coallision (basic - rect)
Create textBox (virtual keyboard for mobile)
Create particle
Atach player (basic movement)
MultipEER (Networking)*
localStarage
App created from visual js always work on all browsers(mobile / desktop). Networking - webRTC - multipeer
Try online at :
https://jsfiddle.net/user/zlatnaspirala/fiddles/
Api look like this :
Application Programming Interface Documentation for Visual JS 0.5 >
GAME_OBJECT is main object in this framework.
1) Adding new game object (name will be 'GO' ):
HELLO_WORLD.ENGINE.MODULES.ACCESS_MODULE("STARTER").NEW_OBJECT("GO" ,
x , y , w , h , speed )
HELLO_WORLD.ENGINE.MODULES.ACCESS_MODULE("STARTER").NEW_OBJECT( "GO" ,
45 , 45 , 10 , 10 , 10)
// 2) Adding image or animation :
// DRAW TYPE can be // 'DRAW_FRAME' no animation // 'LOOP' playing
animation // this number '1111123123' is ID can be any number
//ANIMATION ( surf ,TYPE_, FrameIndex ,source , PARENT , ID , blink_
, min_ , max_ , step , speed_ , opacity_ )
HELLO_WORLD.ENGINE.MODULES.ACCESS_MODULE("STARTER").GAME_OBJECTS.ACCESS("GO").CREATE_ANIMATION(
SURF , "DRAW_FRAME" , 6 , RESOURCE.Tiles , 1111123123 , "no" ,
1,11,1,1,1)
3)Disable draging GO.DRAG = false;
// RESOURCE.NAMEOFFOLDERANIMATION
add folder "Tiles" with images in folder /res/ and run node res.js
// refresh page and you will get
RESOURCE.Tiles ready for use !
// MAKE MODULE ACCESS EASY var
STARTER = HELLO_WORLD.ENGINE.MODULES.ACCESS_MODULE("STARTER");
STARTER.GAME_OBJECTS.ACCESS("GO").CREATE_ANIMATION( SURF ,
"DRAW_FRAME" , 6 , RESOURCE.Tiles , 1111123123 , "no" , 1,11,1,1,1)
//DRAG initial value is true GO.DRAG = false;
//setup quard height = width GO.POSITION.DIMENSION.H = GO.POSITION.DIMENSION.W;
4) EVENTS FOR MOUSE AND MOBILE TOUCH HANDLED
//CLICK OR TOUCH START GO.TAP = function(){
//this make point directing to the game object instance
// this.NAME or this.ANIMATION.CURRENT_FRAME };
GO.TOUCH_DOWN = function(){
STARTER.DESTROY_OBJECT("GO") console.log("THIS MUST BE TERMINATED
ON MOUSE DOWN or TOUCH_DOWN : " + this.NAME);
//this.DESTROY_ME_AFTER_X_SECUND( 100 ); //console.log("THIS MUST BE
TERMINATED ON CLICK : " + this.NAME); };
GO.TOUCH_MOVE = function(){
console.log("HOVER ON OBJECT OR MOBILE TOUCH_MOVE : " + this.NAME); };
GO.TOUCH_UP = function(){
console.log("MOUSE UP ON OBJECT OR MOBILE TOUCH_UP : " + this.NAME); };*
Download git

Categories