not sure what I'm doing wrong here but some select mouse events (drag/drop, onclick and onpress) do not work. onDoubleClick works however. This is what I'm doing.
.js file
var b2Vec2 = Box2D.Common.Math.b2Vec2;
var b2DebugDraw = Box2D.Dynamics.b2DebugDraw;
var b2BodyDef = Box2D.Dynamics.b2BodyDef;
var b2Body = Box2D.Dynamics.b2Body;
var b2FixtureDef = Box2D.Dynamics.b2FixtureDef;
var b2Fixture = Box2D.Dynamics.b2Fixture;
var b2World = Box2D.Dynamics.b2World;
var b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape;
var b2CircleShape = Box2D.Collision.Shapes.b2CircleShape;
var b2DebugDraw = Box2D.Dynamics.b2DebugDraw;
var b2AABB = Box2D.Collision.b2AABB;
var b2ContactListener = Box2D.Dynamics.b2ContactListener;
window.onblur = function(){ Ticker.setPaused(true); PAUSED = true; console.log("paused"); }
window.onfocus = function(){ Ticker.setPaused(false); PAUSED = false; console.log("unpaused"); }
var PAUSED = false;
var Type = {
WALL : 1,
BOULDER : 2
};
var CategoryBits = {
WALL : 0x0001,
BOULDER : 0x0002
};
function Boundary(density, restitution, friction, angularDamping, linearDamping, position, size, scale, categoryBits, maskBits, type, world){
var boundaryFixture = new b2FixtureDef;
boundaryFixture.density = density;
boundaryFixture.restitution = restitution;
boundaryFixture.friction = friction;
boundaryFixture.filter.categoryBits = categoryBits;
boundaryFixture.filter.maskBits = maskBits;
boundaryFixture.shape = new b2PolygonShape;
boundaryFixture.shape.SetAsBox(size.length/scale, size.height/scale);
var boundaryBodyDef = new b2BodyDef;
boundaryBodyDef.type = b2Body.b2_staticBody;
boundaryBodyDef.angularDamping = angularDamping;
boundaryBodyDef.linearDamping = linearDamping;
boundaryBodyDef.position.x = position.x/ scale;
boundaryBodyDef.position.y = position.y/scale;
this.boundary = world.CreateBody(boundaryBodyDef);
this.boundary.CreateFixture(boundaryFixture);
this.boundary.SetUserData(this);
this.type = type;
};
function Position(x, y){
this.x = x;
this.y = y;
};
function Size(length, height){
this.length = length;
this.height = height;
};
function Noir(size, scale, step, debug){
this.GRAVITY = new b2Vec2(0, 10/(scale/5));
this.FPS = 30;
this.SCALE = scale;
this.STEP = step;
this.TIMESTEP = 1/this.STEP;
this.DEBUG = debug;
this.LENGTH = size.length;
this.LENGTH_OFFSET = 20;
this.HEIGHT = size.height;
this.HEIGHT_OFFSET = 10;
this.BOUNDARY_WIDTH = 2;
this.VELOCITY_ITERATIONS = 10;
this.POSITION_ITERATIONS = 10;
this.world;
this.contactListener;
this.canvas;
this.debugCanvas;
this.debugDraw;
this.context;
this.debugContext;
this.stage;
this.previousTime = Date.now();
this.game;
};
Noir.prototype.initCanvas = function(){
this.canvas = document.getElementById('canvas');
this.context = canvas.getContext('2d');
this.stage = new Stage(canvas);
this.stage.snapPixelsEnabled = true;
this.stage.mouseEventsEnabled = true;
//this.stage.onDoubleClick = function(event){ console.log("moving.."); }
this.stage.enableMouseOver();
if(this.DEBUG){
this.debugCanvas = document.getElementById('debugCanvas');
this.debugContext = debugCanvas.getContext('2d');
console.log('Debug on');
}
};
Noir.prototype.initDebug = function(){
this.debugDraw = new b2DebugDraw();
this.debugDraw.SetSprite(this.debugContext);
this.debugDraw.SetDrawScale(this.SCALE);
this.debugDraw.SetFillAlpha(0.7);
this.debugDraw.SetLineThickness(1.0);
this.debugDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit);
this.world.SetDebugDraw(this.debugDraw);
};
Noir.prototype.setContactListener = function(){
this.contactListener = new b2ContactListener;
this.contactListener.events = this;
this.contactListener.BeginContact = function(contact, manifold){
var bodyAUser = contact.GetFixtureA().GetBody().GetUserData();
var bodyBUser = contact.GetFixtureB().GetBody().GetUserData();
/* console.log(bodyAUser.type + " , " + bodyBUser.type); */
if((bodyAUser.type == Type.BOULDER) && (bodyBUser.type == Type.WALL)){ this.events.boulderWallContact(bodyAUser, bodyBUser); }
else if((bodyAUser.type == Type.WALL) && (bodyBUser.type == Type.BOULDER)){ this.events.boulderWallContact(bodyBUser, bodyAUser); }
}
this.world.SetContactListener(this.contactListener);
};
Noir.prototype.boulderWallContact = function(boulder, wall){ boulder.flagToDestroy(); };
Noir.prototype.initPhysics = function(){
this.lastTimestamp = Date.now();
this.world = new b2World(this.GRAVITY, true);
this.setContactListener();
if(this.DEBUG){ this.initDebug(); console.log('Debug initialized'); }
var floor = new Boundary(1, 1, 0.6, 0.6, 0.6, new Position(-(this.LENGTH_OFFSET/2), (this.HEIGHT+ (this.HEIGHT_OFFSET - (this.HEIGHT_OFFSET - 1)))),
new Size((this.LENGTH + this.LENGTH_OFFSET), this.BOUNDARY_WIDTH), this.SCALE, CategoryBits.WALL, CategoryBits.BOULDER, Type.WALL, this.world);
/* var ceiling = new Boundary(1, 1, 0.6, 0.6, 0.6, new Position(-(this.LENGTH_OFFSET/2), (this.HEIGHT_OFFSET - (this.HEIGHT_OFFSET - 1))),
new Size((this.LENGTH + this.LENGTH_OFFSET), this.BOUNDARY_WIDTH), this.SCALE, CategoryBits.WALL, CategoryBits.BOULDER, Type.WALL, this.world); */
var leftFixture = new Boundary(1,1, 0.6, 0.6, 0.6, new Position(-(this.BOUNDARY_WIDTH - (this.BOUNDARY_WIDTH - 1)), -(this.LENGTH_OFFSET/2)),
new Size(this.BOUNDARY_WIDTH, (this.HEIGHT + this.HEIGHT_OFFSET)), this. SCALE, CategoryBits.WALL, CategoryBits.BOULDER, Type.WALL, this.world);
var rightFixture = new Boundary(1,1, 0.6, 0.6, 0.6, new Position((this.LENGTH + (this.LENGTH_OFFSET - (this.LENGTH_OFFSET - 1))), -(this.LENGTH_OFFSET/2)),
new Size(this.BOUNDARY_WIDTH, (this.HEIGHT+ this.HEIGHT_OFFSET)), this.SCALE, CategoryBits.WALL, CategoryBits.BOULDER, Type.WALL, this.world);
};
Noir.prototype.tick = function(){
this.updatePhysics();
this.stage.update();
};
Noir.prototype.initTicker = function(){
Ticker.setFPS(this.FPS);
Ticker.useRAF = true;
Ticker.addListener(this, true);
};
Noir.prototype.init = function(){
this.initCanvas();
this.initTicker();
this.initPhysics();
this.initGame(this.stage, this.world);
var debug = document.getElementById('debug');
};
Noir.prototype.initOnLoadDocument = function(){
console.log('running');
if(document.loaded){ this.init(); }
else{
if(window.addEventListener){ window.addEventListener('load', this.init(), false); }
else { window.attachEvent('onLoad', this.init); }
}
}
Noir.prototype.updatePhysics = function(){
/* remove flagged objects for destruction */
/* update non-flagged objects */
if(!PAUSED){
this.updateGame();
this.world.Step(this.TIMESTEP, this.VELOCITY_ITERATIONS, this.POSITION_ITERATIONS);
this.world.ClearForces();
if(this.DEBUG){
this.world.m_debugDraw.m_sprite.graphics.clear();
this.world.DrawDebugData();
}
}
};
Noir.prototype.initGame = function(){
this.game = new Game(this.stage, this.SCALE, this.world);
this.game.start();
};
Noir.prototype.updateGame = function(){ this.game.update(); }
function Actor(density, restitution, friction, angularDamping, linearDamping, path, position, size, stage, scale, categoryBits, maskBits, type, world){
this.skin = new Bitmap(path);
this.skin.x = position.x;
this.skin.y = position.y;
this.skin.regX = (size.length/2);
this.skin.regY = (size.height/2);
this.skin.snapToPixel = true;
this.skin.mouseEnabled = false;
stage.addChild(this.skin);
var actorFixture = new b2FixtureDef;
actorFixture.density = density;
actorFixture.restitution = restitution;
actorFixture.friction = friction;
actorFixture.filter.categoryBits = categoryBits;
actorFixture.filter.maskBits = maskBits;
actorFixture.shape = new b2PolygonShape;
actorFixture.shape.SetAsBox((size.length/2)/scale, (size.height/2)/scale);
var actorBodyDef = new b2BodyDef;
actorBodyDef.type = b2Body.b2_dynamicBody;
actorBodyDef.angularDamping = angularDamping;
actorBodyDef.linearDamping = linearDamping;
actorBodyDef.position.x = this.skin.x/scale;
actorBodyDef.position.y = this.skin.y/scale;
this.body = world.CreateBody(actorBodyDef);
this.body.CreateFixture(actorFixture);
this.body.SetUserData(this);
this.type = type;
this.destroy = false;
};
Actor.prototype.flagToDestroy = function(){ this.destroy = true; };
Actor.prototype.remove = function(game){
game.stage.removeChild(this.skin);
game.world.DestroyBody(this.body);
game.actors.splice(game.actors.indexOf(this),1);
};
Actor.prototype.update = function(scale){
this.skin.rotation = this.body.GetAngle() * (180/Math.PI);
this.skin.x = this.body.GetWorldCenter().x * scale;
this.skin.y = this.body.GetWorldCenter().y * scale;
};
function Icon(path, position, size, stage){
this.skin = new Bitmap(path);
this.skin.x = position.x;
this.skin.y = position.y;
this.skin.regX = (size.length/2);
this.skin.regY = (size.height/2);
stage.addChild(this.skin);
//this.skin.onDoubleClick = function(event){ alert("click click"); }
this.skin.onClick = function(event){ alert("click"); }
this.skin.onPress = function(event){ console.log("pressing"); }
};
function Game(stage, scale, world){
this.scale = scale;
this.stage = stage;
this.world = world;
this.boulderSpawnDelayCounter = 0;
this.actors = [];
this.icon;
};
Game.prototype.start = function(){
var position = new Position(400, 200);
var size = new Size(50, 50);
console.log(this);
this.icon = new Icon("images/bird.png", position, size, this.stage);
};
Game.prototype.controlledSpawn = function(stage, scale, world){
var spawnInterval = (50 + Math.round(Math.random() * 10));
this.boulderSpawnDelayCounter++;
if(this.boulderSpawnDelayCounter % spawnInterval === 0){
this.boulderSpawnDelayCounter = 0;
this.boulderSpawn();
}
};
Game.prototype.boulderSpawn = function(stage, scale, world){
var position = new Position((100 + Math.round(Math.random() * 250)), -20);
var size = new Size(50, 50);
this.actors.push(new Actor(0.2, 0.6, 0.3, 0.3, 0.3, "images/bird.png", position, size, this.stage, this.scale, CategoryBits.BOULDER, CategoryBits.WALL, Type.BOULDER, this.world));
};
Game.prototype.update = function(){
this.controlledSpawn();
for(idx = 0; idx < this.actors.length; ++idx){
if(this.actors[idx].destroy == true){ this.actors[idx].remove(this); }}
for(idx = 0; idx < this.actors.length; ++idx){ this.actors[idx].update(this.scale); }
};
.html file
<!doctype html>
<html xmlns:og="http://ogp.me/ns#">
<head>
<meta charset="utf-8">
<title>Noir test</title>
<link href="css/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<canvas width="500" height="500" id="canvas"></canvas>
<canvas width="500" height="500" id="debugCanvas"></canvas>
<script> var createjs = window </script>
<script type="text/javascript" src="libs/easeljs-0.5.0.min.js"></script>
<script type="text/javascript" src="libs/Box2dWeb-2.1.a.3.min.js"></script>
<script type="text/javascript" src="js/noir.js"></script>
<script> var noir = new Noir(new Size(500, 500), 30, 20, false); noir.initOnLoadDocument()</script>
</body>
</html>
I'm working with this on a local server so the server security issue triggering this similar behaviour for remote servers doesn't apply (I think). Guys, I'm stumped here. Your help will be very much appreciated. Thanks.
Without seeing your CSS, I would guess that your debug canvas is layered overtop of your main canvas. If this is the case, the debug canvas will be the target for any mouse events, preventing your main canvas (and the related Stage) from receiving them.
Due to a bug (recently fixed in the NEXT version), EaselJS subscribes to double click events on the window, instead of on the canvas, which is likely why onDoubleClick is working for you.
Also, it might be worth checking out the newer version of EaselJS. v0.7.0 includes a great new event model, and v0.7.1 will be out shortly with the fix for double click.
Related
I want to have onclick and hover functionality simultaneously but if you have clicked somewhere then hover should not work until I click somewhere else. I have tried alot but I didn't find any working code. Kindly help
canvas.addEventListener('mousedown', function(evt) {
}, false);
canvas.onmousemove = function(evt) {
};
Well, I am not quite sure what you need and why you need it. But, in that short piece of code you wrote I saw the word "canvas" and thought "what the heck, that could be fun!". I have not much experience with the canvas element since earlier, so I realize there may be better ways of writing this code.
But, I hope what I wrote in the below example is at least close to what you were looking for. Otherwise, go nuts and change and adapt the way you like... and while you do that, try to learn something of it.
var Canvas = function() {
this.$canvas = $('canvas');
this.$currPos = $('#currPos');
this.$currClick = $('#currClick');
this.$clickInfo = $('#clickInfo');
this.canvsWidth = 150;
this.cavasHeight = 150;
this.ctx = ctx = this.$canvas[0].getContext('2d');
this.rect = this.$canvas[0].getBoundingClientRect();
this.squares = [];
this.sqm = 50;
this.tracker = 0;
this.latestHover = {};
this._events();
this._prepare();
};
Canvas.prototype._events = function() {
var self = this;
this.$canvas.on('mousemove', function(e) {
var posX = e.clientX - self.rect.left,
posY = e.clientY - self.rect.top,
newX = Math.floor(posX / self.sqm),
newY = Math.floor(posY / self.sqm);
if($.isEmptyObject(self.latestHover) || (self.latestHover.x !== newX || self.latestHover.y !== newY)) {
self.latestHover.x = newX;
self.latestHover.y = newY;
self.squares.map(function(k, v) {
let obj = self.squares[v];
if(!obj.fixedBackground) obj.reverseBackgroundColor();
});
var square = self.findObject(newX, newY)[0];
if(square) {
square.setBackgroundColor('#ff0000');
self.$currPos.html(newX +'x'+ newY);
self._redraw();
}
}
});
this.$canvas.on('click', function() {
if(self.tracker === 2) {
return self._reset();
}
if(!($.isEmptyObject(self.latestHover))) {
var x = self.latestHover.x,
y = self.latestHover.y;
var square = self.findObject(x, y)[0];
square.setFixedBackground();
self.$currClick.html(x +'x'+ y);
self.setTracker();
}
});
};
Canvas.prototype._prepare = function() {
for(var row = 0; row < 3; row++) {
for(var col = 0; col < 3; col++) {
this.squares.push(new Square(row, col, this.ctx, this.sqm));
}
}
};
Canvas.prototype._redraw = function() {
var self = this;
this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
this.squares.filter(function(k, v) {
self.squares[v].draw();
});
};
Canvas.prototype.setTracker = function() {
this.tracker++;
if(this.tracker === 2) this.$clickInfo.html('Click one more time to start over');
};
Canvas.prototype.findObject = function(x, y) {
var self = this;
return square = self.squares.filter(function(k, v) {
var obj = self.squares[v];
if(obj.posX === x && obj.posY === y) return obj;
});
};
Canvas.prototype._reset = function() {
var self = this;
this.squares.map(function(k, v) {
let obj = self.squares[v];
obj.reverseBackgroundColor();
obj.unsetFixedBackground();
});
this.$currClick.html('');
this.$clickInfo.html('');
this.tracker = 0;
this._redraw();
};
var Square = function(x, y, ctx, sqm) {
this.ctx = ctx;
this.sqm = sqm;
this.posX = x;
this.posY = y;
this.background = '#fff';
this.strokeThickness = 1;
this.fixedBackground = false;
this.draw();
};
Square.prototype.setBackgroundColor = function(color) {
return this.background = color;
};
Square.prototype.reverseBackgroundColor = function() {
return this.background = '#fff';
};
Square.prototype.setFixedBackground = function() {
return this.fixedBackground = true;
};
Square.prototype.unsetFixedBackground = function() {
return this.fixedBackground = false;
};
Square.prototype.draw = function() {
this.ctx.fillStyle = this.background;
this.ctx.fillRect(this.posX * this.sqm, this.posY * this.sqm, this.sqm, this.sqm);
this.ctx.strokeRect(this.posX * this.sqm, this.posY * this.sqm, this.sqm, this.sqm);
};
window.Canvas = new Canvas();
canvas {
border: 1px solid #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas width="150" height="150"></canvas>
<div>
Current position: <span id="currPos"></span> <br/>
Last click: <span id="currClick"></span> <span id="clickInfo"></span>
</div>
I want to write Bitmap eraser on easelJS. I think, i'm on half of my road to do this....
Here is demo:
http://jsfiddle.net/bordeux/g2Lwvsuv/2/
and my code:
var example = function() {
this.constructor.apply(this, arguments);
};
example.prototype.constructor = function() {
this.$canvas = $("canvas");
this.container = {};
this.objects = {};
this.resizeEvents = [];
this.prepareCanvas();
this.refreshSize();
this.bindEvents();
};
example.prototype.bindEvents = function() {
var self = this;
$(window).resize(function(){
self.refreshSize();
});
};
example.prototype.refreshSize = function() {
this.stage.canvas.width = window.innerWidth;
this.stage.canvas.height = window.innerHeight;
this.resizeEvents.forEach(function(item) {
item();
});
};
example.prototype.getObject = function(name) {
return this.objects[name];
};
example.prototype.setObject = function(name, obj) {
this.objects[name] = obj;
return obj;
};
example.prototype.addResizeEvent = function(foo) {
this.resizeEvents.push(foo);
return this;
};
example.prototype.initCursor = function() {
var self = this;
var size = 50;
/**
* Circle cursor
*/
var circle = new createjs.Shape();
circle.graphics.setStrokeStyle(2).beginStroke("#171717").drawCircle(0, 0, size);
/**
* Hit area
*/
var hit = new createjs.Shape();
hit.graphics.beginFill("#000").drawCircle(0, 0, size);
circle.hitArea = hit;
var container = this.getContainer("cursor");
container.addChild(circle);
this.stage.on("stagemousemove", function(evt) {
circle.setTransform(evt.stageX, evt.stageY);
this.setChildIndex( container, this.getNumChildren()-1);
});
var drawing = this.setObject("image.mask", new createjs.Shape());
drawing.visible = false;
var lastPoint = new createjs.Point();
container.addChild(drawing);
circle.on("mousedown", function(event) {
lastPoint.x = event.stageX;
lastPoint.y = event.stageY;
});
circle.on("pressmove", function(event) {
drawing.graphics
.setStrokeStyle(100, "round", "round")
.beginStroke("rgba(255, 255, 255, 0.2)")
.beginRadialGradientFill(
["rgba(0,0,0,0)", "rgba(0,0,0,1)"],
[0.1, 1],
50, 50, 0,
50, 50, 50
)
.moveTo(lastPoint.x, lastPoint.y)
.lt(event.stageX, event.stageY);
lastPoint.x = event.stageX;
lastPoint.y = event.stageY;
self.updateCache();
});
circle.on("pressup", function(event) {
self.updateCache();
});
};
example.prototype.updateCache = function(update) {
(update === undefined) && (update = false);
var drawingCanvas = this.getObject("image.mask");
var image = this.getObject("image");
if (update) {
drawingCanvas.updateCache();
} else {
drawingCanvas.cache(0, 0, image.image.naturalWidth, image.image.naturalHeight);
}
image.filters = [
new createjs.AlphaMaskFilter(drawingCanvas.cacheCanvas)
];
if (update) {
image.updateCache(0, 0, image.image.naturalWidth, image.image.naturalHeight);
} else {
image.cache(0, 0, image.image.naturalWidth, image.image.naturalHeight);
}
};
example.prototype.prepareCanvas = function() {
this.stage = new createjs.Stage(this.$canvas[0]);
createjs.Ticker.setFPS(60);
createjs.Ticker.addEventListener("tick", this.stage);
this.initCursor();
this.loadImage();
};
/**
* Get container. If not exist, this function create new one
* #param {String} name
* #returns {createjs.Container}
*/
example.prototype.getContainer = function(name) {
if(this.container[name]){
return this.container[name];
}
this.container[name] = new createjs.Container();
this.stage.addChild(this.container[name]);
return this.container[name];
};
example.prototype.loadImage = function() {
var self = this;
var url = "https://upload.wikimedia.org/wikipedia/commons/thumb/a/aa/Logo_Google_2013_Official.svg/1280px-Logo_Google_2013_Official.svg.png";
var background = this.setObject("image.background", new createjs.Shape());
this.getContainer("image").addChild(background);
var image = null;
return utils.image(url).then(function(img){
image = img;
self.getContainer("image").addChild(self.setObject(
"image",
new createjs.Bitmap(img)
));
self.updateCache(false);
return utils.image("http://i.imgur.com/JKaeYwv.png");
}).then(function(imgBackground){
background
.graphics
.beginBitmapFill(imgBackground,'repeat')
.drawRect(0,0, image.naturalWidth, image.naturalHeight);
});
};
utils = {};
utils.image = function(url){
var deferred = Q.defer();
//deferred.resolve(text);
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function(){
deferred.resolve(this);
};
img.onerror = function(){
deferred.reject(arguments);
};
img.src = url;
return deferred.promise;
};
$(function(){
var test = new example();
});
But when i draw something on my canvas, my path of draw showing image behind mask... This is opposed result what i want.
I want remove part of image (like eraser in Photoshop). I don't know what i should do next...
Thanks
You can use compositeOperation in conjunction with layers or caching to "erase" content. For example, if you use updateCache("source-over"), that will draw the current visual content over the existing cache (normal compositing). However, if you use updateCache("destination-out"), that will essentially punch out the current content from the existing cache, which gives you an eraser effect.
Here's a simple example of this in action: http://jsfiddle.net/17xec9y5/4
I want to set a new position of body on BeginContact event but it's still not functional. It's writed in JavaSript with drawing to canvas but it doesn't matter for Box2d. In HTML file in body is only empty canvas, nothing else. Here is my code:
In the beginning of JS file are only declarated some variables.
Vec2 = Box2D.Common.Math.b2Vec2;
BodyDef = Box2D.Dynamics.b2BodyDef;
Body = Box2D.Dynamics.b2Body;
FixtureDef = Box2D.Dynamics.b2FixtureDef;
Fixture = Box2D.Dynamics.b2Fixture;
World = Box2D.Dynamics.b2World;
PolygonShape = Box2D.Collision.Shapes.b2PolygonShape;
DebugDraw = Box2D.Dynamics.b2DebugDraw;
var player;
It's followed by a setup function which is called in the beginning.
function setup()
{
canvas = document.getElementById("collisionCanvas");
context = canvas.getContext('2d');
document.getElementsByTagName('body')[0].style.backgroundColor = "black";
canvas.style.backgroundColor = "white";
canvas.width = 320;
canvas.height = 320;
world = new World(new Vec2(0, 10), false);
//Point of the problem!!!
//setting contact listener
var listener = new Box2D.Dynamics.b2ContactListener;
listener.BeginContact = function(contact)
{
var body1 = contact.GetFixtureA().GetBody();
var body2 = contact.GetFixtureB().GetBody();
if(body1.GetUserData().type == "player")
{
body1.SetPosition({x:5, y:5});
}
else
{
body2.SetPosition({x:5, y:5});
}
}
world.SetContactListener(listener);
var fixDef = new FixtureDef;
fixDef.density = 1.0;
fixDef.friction = 0.5;
fixDef.restitution = 0.2;
var bodyDef = new BodyDef;
//creating ground
bodyDef.type = Body.b2_staticBody;
bodyDef.position.x = convertPixelsToMeters(160);
bodyDef.position.y = convertPixelsToMeters(320-32/2);
bodyDef.userData = {type: "static"};
fixDef.shape = new PolygonShape;
fixDef.shape.SetAsBox(convertPixelsToMeters(canvas.width/2), convertPixelsToMeters(32/2));
world.CreateBody(bodyDef).CreateFixture(fixDef);
//creating player
bodyDef.type = Body.b2_dynamicBody;
bodyDef.fixedRotation = true;
bodyDef.position.x = convertPixelsToMeters(160);
bodyDef.position.y = convertPixelsToMeters(160);
bodyDef.userData = {type: "player"};
fixDef.shape = new PolygonShape;
fixDef.shape.SetAsBox(convertPixelsToMeters(16), convertPixelsToMeters(16));
player = world.CreateBody(bodyDef);
player.CreateFixture(fixDef);
//setup debug draw
var debugDraw = new DebugDraw();
debugDraw.SetSprite(document.getElementById("collisionCanvas").getContext("2d"));
debugDraw.SetDrawScale(32.0);
debugDraw.SetFillAlpha(0.3);
debugDraw.SetLineThickness(1.0);
debugDraw.SetFlags(DebugDraw.e_shapeBit | DebugDraw.e_jointBit);
world.SetDebugDraw(debugDraw);
window.setInterval(update, 1000 / 60);
}
And in the end are only update function, one helping function and that's it.
function update()
{
world.Step(
1 / 60 //frame-rate
, 10 //velocity iterations
, 10 //position iterations
);
world.DrawDebugData();
world.ClearForces();
}
function convertPixelsToMeters(x)
{
return x*0.03125;
}
$(function(){
setup();
})
Important is only the middle code where is BeginContact event where is calling the SetPosition function which doesn't work.
I tried change position in other places, for example on KeyDown event and there it was correct, so it's for me understandable why it doesn't work.
In the b2Contactlistner method we can not change any prperty or position.
You can take any boolean variable and make it true when in beign contact and if change the position of body according to boolean variable.
as in your code.......
var bodyyy;
var boolennn
listener.BeginContact = function(contact)
{
var body1 = contact.GetFixtureA().GetBody();
var body2 = contact.GetFixtureB().GetBody();
if(body1.GetUserData().type == "player")
{
//body1.SetPosition({x:5, y:5});
bodyyy = body1;
booleannn = true;
}
else
{
// body2.SetPosition({x:5, y:5});
bodyyy = body2;
boolennn = true;
}
}
Now In your Update method
if(booleann)
{
bodyyy.SetPosition({x:5, y:5})
}
SORRY I Donot know syntax of java script
I have the following code in Box2D, I want to move my dynamic body to the point where the mouse is click. Also in the future i want to be able to remove the dynamic body, I am not able to find anything equivalent to world.DeleteBody(...). Please Help.
var world;
var b2Vec2 = Box2D.Common.Math.b2Vec2
, b2BodyDef = Box2D.Dynamics.b2BodyDef
, b2Body = Box2D.Dynamics.b2Body
, b2FixtureDef = Box2D.Dynamics.b2FixtureDef
, b2Fixture = Box2D.Dynamics.b2Fixture
, b2World = Box2D.Dynamics.b2World
, b2MassData = Box2D.Collision.Shapes.b2MassData
, b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape
, b2CircleShape = Box2D.Collision.Shapes.b2CircleShape
, b2DebugDraw = Box2D.Dynamics.b2DebugDraw
;
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var mouseX, mouseY, isMouseDown;
var bBallBody, bBallbodyDef;
function init() {
world = new b2World(
new b2Vec2(0, 10) //gravity
, true //allow sleep
);
setupWorld() ;
//setup debug draw
var debugDraw = new b2DebugDraw();
debugDraw.SetSprite(document.getElementById("canvas").getContext("2d"));
debugDraw.SetDrawScale(1.0);
debugDraw.SetFillAlpha(0.3);
debugDraw.SetLineThickness(1.0);
debugDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit);
world.SetDebugDraw(debugDraw);
window.setInterval(update, 1000 / 60);
};
function setupWorld() {
setupGround();
addBouncingBall();
}
function setupGround() {
var fixDef = new b2FixtureDef;
fixDef.density = 1.0;
fixDef.friction = 0.5;
fixDef.restitution = 0.2;
var bodyDef = new b2BodyDef;
//create ground
bodyDef.type = b2Body.b2_staticBody;
bodyDef.position.x = 300;
bodyDef.position.y = 400;
fixDef.shape = new b2PolygonShape;
fixDef.shape.SetAsBox(290, 10);
world.CreateBody(bodyDef).CreateFixture(fixDef);
}
function addBouncingBall() {
var fixDef = new b2FixtureDef;
fixDef.density = 1.0;
fixDef.friction = 1.0;
fixDef.restitution = 0.1;
var bBallbodyDef = new b2BodyDef;
bBallbodyDef.type = b2Body.b2_dynamicBody;
fixDef.shape = new b2CircleShape(Math.random() + 30);
bBallbodyDef.position.x = Math.random() * 300;
bBallbodyDef.position.y = Math.random() * 300;
bBallBody = world.CreateBody(bBallbodyDef).CreateFixture(fixDef);
console.log(bBallBody.m_body.GetPosition().x);
};
document.addEventListener("mousedown", handleMouseMove, true);
function handleMouseMove(e) {
isMouseDown = true;
mouseX = e.clientX;
mouseY = e.clientY;
};
function update() {
if(isMouseDown)
{
for (b = world.GetBodyList() ; b; b = b.GetNext()) {
if (b.GetType() == b2Body.b2_dynamicBody) {
console.log(b.x, b.y);
b.x = 100;
b.y = 100;
}
}
isMouseDown = false;
}
world.Step(1 / 60, 10, 10);
world.DrawDebugData();
world.ClearForces();
};
Update:
Deletion of an object from the world is done as follows,
Create a Timer to Schdule the deletion of the object.
window.setInterval(removeObjScheduledForRemoval, 1000/90);
Collect the objects to be deleted in a Array.
var bricksScheduledForRemoval = Array();
var index = -1;
function removeObjScheduledForRemoval()
{
for(var i = 0; i <= index; i++){
world.DestroyBody(bricksScheduledForRemoval[i]);
bricksScheduledForRemoval[i] = null;
}
bricksScheduledForRemoval = Array();
index = -1;
}
The complete code is available here,
http://box2dinabox.blogspot.in/2012/07/the-completed-bananamonkey-game.html
The documentation for box2dweb is nowhere near as comprehensive as it is for the original C version, so consider searching for "box2d" instead of "box2dweb". Also, looking into the source and searching for the spelling of certain methods could be helpful. Or just look into the box2d flash documentation. Basically, box2dweb has the methods DestroyJoint and DestroyBody.
For more considerations, this could be helpful: http://www.iforce2d.net/b2dtut/removing-bodies
You can remove the body or change the static body to dynamic as this game example does.
http://pixsansar.com/box2dweb-jumping-and-puzzle-ball-level4
Box2dweb has removebody or changeBodyType option, see the source code of it.
I am trying to get the distance between my character and the ground, I have found something that looks like it should do what I want but it has been written for another version of box2d.
Original:
float targetHeight = 3;
float springConstant = 100;
//make the ray at least as long as the target distance
b2Vec2 startOfRay = m_hovercarBody->GetPosition();
b2Vec2 endOfRay = m_hovercarBody->GetWorldPoint( b2Vec2(0,-5) );
overcarRayCastClosestCallback callback;
m_world->RayCast(&callback, startOfRay, endOfRay);
if ( callback.m_hit ) {
float distanceAboveGround = (startOfRay - callback.m_point).Length();
//dont do anything if too far above ground
if ( distanceAboveGround < targetHeight ) {
float distanceAwayFromTargetHeight = targetHeight - distanceAboveGround;
m_hovercarBody->ApplyForce( b2Vec2(0,springConstant*distanceAwayFromTargetHeight),
m_hovercarBody->GetWorldCenter() );
}
}
I have tried to change it to what I think it should be but it doesn't even call the callback.
var targetHeight = 3;
var springConstant = 100;
//make the ray at least as long as the target distance
startOfRay = new b2Vec2(m_hovercarBody.GetPosition());
endOfRay = new b2Vec(m_hovercarBody.GetWorldPoint( b2Vec2(0,-5)));
function callback(raycast){
if ( raycast.m_hit ) {
var distanceAboveGround = (startOfRay - raycast.m_point).Length();
//dont do anything if too far above ground
if ( distanceAboveGround < targetHeight ) {
var distanceAwayFromTargetHeight = targetHeight - distanceAboveGround;
m_hovercarBody.ApplyForce( b2Vec2(0,springConstant*distanceAwayFromTargetHeight),
m_hovercarBody.GetWorldCenter() );
}
}
}
m_world.RayCast(callback, startOfRay, endOfRay);
Any idea how to convert it to work with box2dweb?
Thanks
It might be that the original bit of code was written for a platform where the coordinate system works differently.
In a Canvas element, the coordinate system starts from the top left corner, meaning that m_hovercarBody.GetWorldPoint( b2Vec2(0,-5)) is checking for a point above the character, rather than below.
I'm not sure about the rest of the code but try changing that to m_hovercarBody.GetWorldPoint( b2Vec2(0,5)) and see what happens.
EDIT:
I think actually the problem is with the way you've structured your callback. Looking up the reference for the Raycast function would reveal more.
(The Javascript version of Box2D you're using is an automatic port of the Actionscript one. Given the two have fairly similar syntax, you can use the reference for Flash.)
The original code you posted seems to be C++, but I don't know much about its syntax. It seems there's some sort of class that does the raycasting (overcarRayCastClosestCallback). You can either look for that, or try and build your own callback function according to the first link I posted. It would be something along the lines of:
function customRaycastCallback(fixture, normal, fraction) {
// you can, for instance, check if fixture belongs to the ground
// or something else, then handle things accordingly
if( /* fixture belongs to ground */ ) {
// you've got the fraction of the original length of the raycast!
// you can use this to determine the distance
// between the character and the ground
return fraction;
}
else {
// continue looking
return 1;
}
}
Try running this on your browser. I coded this when I was learning sensor and RAYCAST in Box2Dweb. Hope it helps.
<html>
<head>
<title>Box2dWeb Demo</title>
</head>
<body>
<canvas id="canvas" width="600" height="420" style="background-color:#333333;" ></canvas>
<div id="cc" style="position:absolute; right:0; top:100px; width:500px; height:50px; margin:0;"></div>
</body>
<script type="text/javascript" src="Box2dWeb-2.1.a.3.js"></script>
<script type="text/javascript" src="jquery-1.7.2.js"></script>
<script type="text/javascript">
var b2Vec2 = Box2D.Common.Math.b2Vec2
, b2BodyDef = Box2D.Dynamics.b2BodyDef
, b2Body = Box2D.Dynamics.b2Body
, b2FixtureDef = Box2D.Dynamics.b2FixtureDef
, b2World = Box2D.Dynamics.b2World
, b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape
, b2CircleShape = Box2D.Collision.Shapes.b2CircleShape
, b2ContactFilter = Box2D.Dynamics.b2ContactFilter
, b2MouseJointDef = Box2D.Dynamics.Joints.b2MouseJointDef
, b2DebugDraw = Box2D.Dynamics.b2DebugDraw
, b2Fixture = Box2D.Dynamics.b2Fixture
, b2AABB = Box2D.Collision.b2AABB
, b2WorldManifold = Box2D.Collision.b2WorldManifold
, b2ManifoldPoint = Box2D.Collision.b2ManifoldPoint
, b2RayCastInput = Box2D.Collision.b2RayCastInput
, b2RayCastOutput = Box2D.Collision.b2RayCastOutput
, b2Color = Box2D.Common.b2Color;
var world = new b2World(new b2Vec2(0,10), true);
var canvas = $('#canvas');
var context = canvas.get(0).getContext('2d');
//box
var bodyDef = new b2BodyDef;
bodyDef.type = b2Body.b2_dynamicBody;
bodyDef.position.Set(9,7);
bodyDef.userData = 'box';
var fixDef = new b2FixtureDef;
fixDef.filter.categoryBits = 1;
fixDef.density = 10.0;
fixDef.friction = 0.5;
fixDef.restitution = .5;
fixDef.shape = new b2PolygonShape;
fixDef.shape.SetAsBox(1,5);
var box1 = world.CreateBody(bodyDef);
box1.CreateFixture(fixDef);
//circle
var bodyDef2 = new b2BodyDef;
bodyDef2.type = b2Body.b2_dynamicBody;
bodyDef2.position.Set(4,8);
bodyDef2.userData = 'obj';
var fixDef2 = new b2FixtureDef;
fixDef2.filter.categoryBits = 2;
fixDef2.filter.maskBits = 13;
fixDef2.density = 10.0;
fixDef2.friction = 0.5;
fixDef2.restitution = .2;
fixDef2.shape = new b2CircleShape(1);
//circlesensor
var cc = new b2FixtureDef;
cc.shape = new b2CircleShape(2);
cc.shape.SetLocalPosition(new b2Vec2(0 ,0));
cc.density = 0;
cc.isSensor = true;
cc.filter.categoryBits = 8;
var wheel = world.CreateBody(bodyDef2);
wheel.CreateFixture(fixDef2);
wheel.CreateFixture(cc);
//create a ground
var holderDef = new b2BodyDef;
holderDef.type = b2Body.b2_staticBody;
holderDef.userData = "ground";
holderDef.position.Set(10, 14);
var fd = new b2FixtureDef;
fd.filter.categoryBits = 4;
fd.shape = new b2PolygonShape;
fd.shape.SetAsBox(10,1);
var ground = world.CreateBody(holderDef);
ground.CreateFixture(fd);
//create another static body
var holderDef = new b2BodyDef;
holderDef.type = b2Body.b2_staticBody;
holderDef.position.Set(10, 20);
var temp = world.CreateBody(holderDef);
temp.CreateFixture(fd);
var c=0;
$(window).keydown(function(e) {
$('#aa').html(++c);
code = e.keyCode;
if(c==1) {
if(code == 38 && onground)
wheel.SetLinearVelocity(new b2Vec2(0,-10));
if(code == 39)
wheel.ApplyForce(new b2Vec2(1000,0), box1.GetWorldPoint(new b2Vec2(0,0)));
if(code == 37)
wheel.ApplyForce(new b2Vec2(-1000,0), box1.GetWorldPoint(new b2Vec2(0,0)));
}
});
$(window).keyup(function(e) {
c=0;
});
var listener = new Box2D.Dynamics.b2ContactListener;
listener.BeginContact = function(contact) {
if(contact.GetFixtureA().GetBody().GetUserData()== 'obj' || contact.GetFixtureB().GetBody().GetUserData()== 'obj' ) // think about why we don't use fixture's userData directly.
onground = true;// don't put 'var' here!
fxA=contact.GetFixtureA();
fxB=contact.GetFixtureB();
sA=fxA.IsSensor();
sB=fxB.IsSensor();
if((sA && !sB) || (sB && !sA)) {
if(sA) {
$('#cc').prepend(contact.GetFixtureB().GetBody().GetUserData() + ' is in the viscinity of body '+contact.GetFixtureA().GetBody().GetUserData()+'<br>');
}
else {
$('#cc').prepend(contact.GetFixtureA().GetBody().GetUserData() + ' is in the viscinity of body '+contact.GetFixtureB().GetBody().GetUserData()+'<br>');
}
}
}
listener.EndContact = function(contact) {
if (contact.GetFixtureA().GetBody().GetUserData()== 'obj' || contact.GetFixtureB().GetBody().GetUserData()== 'obj' )
onground = false;
}
var debugDraw = new b2DebugDraw();
debugDraw.SetSprite ( document.getElementById ("canvas").getContext ("2d"));
debugDraw.SetDrawScale(30); //define scale
debugDraw.SetAlpha(1);
debugDraw.SetFillAlpha(.3); //define transparency
debugDraw.SetLineThickness(1.0);
debugDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit);
world.SetDebugDraw(debugDraw);
window.setInterval(update,1000/60);
//mouse
var mouseX, mouseY, mousePVec, isMouseDown, selectedBody, mouseJoint;
var canvasPosition = getElementPosition(document.getElementById("canvas"));
document.addEventListener("mousedown", function(e) {
isMouseDown = true;
handleMouseMove(e);
document.addEventListener("mousemove", handleMouseMove, true);
}, true);
document.addEventListener("mouseup", function() {
document.removeEventListener("mousemove", handleMouseMove, true);
isMouseDown = false;
mouseX = undefined;
mouseY = undefined;
}, true);
function handleMouseMove(e) {
mouseX = (e.clientX - canvasPosition.x) / 30;
mouseY = (e.clientY - canvasPosition.y) / 30;
};
function getBodyAtMouse() {
mousePVec = new b2Vec2(mouseX, mouseY);
var aabb = new b2AABB();
aabb.lowerBound.Set(mouseX - 0.001, mouseY - 0.001);
aabb.upperBound.Set(mouseX + 0.001, mouseY + 0.001);
// Query the world for overlapping shapes.
selectedBody = null;
world.QueryAABB(getBodyCB, aabb);
return selectedBody;
}
function getBodyCB(fixture) {
if(fixture.GetBody().GetType() != b2Body.b2_staticBody) {
if(fixture.GetShape().TestPoint(fixture.GetBody().GetTransform(), mousePVec)) {
selectedBody = fixture.GetBody();
return false;
}
}
return true;
}
//at global scope
var currentRayAngle = 0;
var input = new b2RayCastInput();
var output = new b2RayCastOutput();
var b = new b2BodyDef();
var f = new b2FixtureDef();
var closestFraction = 1;
var intersectionNormal = new b2Vec2(0,0);
var intersectionPoint = new b2Vec2();
rayLength = 25; //long enough to hit the walls
var p1 = new b2Vec2( 11, 7 ); //center of scene
var p2 = new b2Vec2();
var normalEnd = new b2Vec2();
function update() {
if(isMouseDown && (!mouseJoint)) {
var body = getBodyAtMouse();
if(body) {
var md = new b2MouseJointDef();
md.bodyA = world.GetGroundBody();
md.bodyB = body;
md.target.Set(mouseX, mouseY);
md.collideConnected = true;
md.maxForce = 300.0 * body.GetMass();
mouseJoint = world.CreateJoint(md);
body.SetAwake(true);
}
}
if(mouseJoint) {
if(isMouseDown) {
mouseJoint.SetTarget(new b2Vec2(mouseX, mouseY));
} else {
world.DestroyJoint(mouseJoint);
mouseJoint = null;
}
}
world.Step(1 / 60, 10, 10);
world.DrawDebugData();
world.ClearForces();
world.SetContactListener(listener);
ray();
};
function ray() {
//in Step() function
var k = 360/20;
var t = k/60;
var DEGTORAD = Math.PI/180;
currentRayAngle += t * DEGTORAD; //one revolution every 20 seconds
//console.log(currentRayAngle*(180/Math.PI));
//calculate points of ray
p2.x = p1.x + rayLength * Math.sin(currentRayAngle);
p2.y = p1.y + rayLength * Math.cos(currentRayAngle);
input.p1 = p1;
input.p2 = p2;
input.maxFraction = 1;
closestFraction = 1;
var b = new b2BodyDef();
var f = new b2FixtureDef();
for(b = world.GetBodyList(); b; b = b.GetNext()) {
for(f = b.GetFixtureList(); f; f = f.GetNext()) {
if(!f.RayCast(output, input))
continue;
else if(output.fraction < closestFraction) {
closestFraction = output.fraction;
intersectionNormal = output.normal;
}
}
}
intersectionPoint.x = p1.x + closestFraction * (p2.x - p1.x);
intersectionPoint.y = p1.y + closestFraction * (p2.y - p1.y);
normalEnd.x = intersectionPoint.x + intersectionNormal.x;
normalEnd.y = intersectionPoint.y + intersectionNormal.y;
context.strokeStyle = "rgb(255, 255, 255)";
context.beginPath(); // Start the path
context.moveTo(p1.x*30,p1.y*30); // Set the path origin
context.lineTo(intersectionPoint.x*30, intersectionPoint.y*30); // Set the path destination
context.closePath(); // Close the path
context.stroke();
context.beginPath(); // Start the path
context.moveTo(intersectionPoint.x*30, intersectionPoint.y*30); // Set the path origin
context.lineTo(normalEnd.x*30, normalEnd.y*30); // Set the path destination
context.closePath(); // Close the path
context.stroke(); // Outline the path
}
//helpers
//http://js-tut.aardon.de/js-tut/tutorial/position.html
function getElementPosition(element) {
var elem=element, tagname="", x=0, y=0;
while((typeof(elem) == "object") && (typeof(elem.tagName) != "undefined")) {
y += elem.offsetTop;
x += elem.offsetLeft;
tagname = elem.tagName.toUpperCase();
if(tagname == "BODY")
elem=0;
if(typeof(elem) == "object") {
if(typeof(elem.offsetParent) == "object")
elem = elem.offsetParent;
}
}
return {x: x, y: y};
}
</script>
</html>
Here's a Raycast in Box2dWeb that I got working:
var p1 = new b2Vec2(body.GetPosition().x, body.GetPosition().y); //center of scene
var p2 = new b2Vec2(body.GetPosition().x, body.GetPosition().y + 5); //center of scene
world.RayCast(function(x){
console.log("You've got something under you");
}, p1,p2);