I'm having a terrible time trying to show/hide a mesh in my babylon.js scene with a button. I assumed I could create a function that would show/hide meshes and then call said button from my page to affect my scene and wrote the following:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="assets/js/babylon.js"></script>
<script src="assets/js/hand-1.3.8.js"></script>
<script src="assets/js/cannon.js"></script> <!-- optional physics engine -->
</head>
<body>
<div id="container">
<!-- Page Content -->
<div id="content">
<div id="tableBuilder">
<div id='cssmenu'>
<ul id="tops">
<button type="button" onclick="showTop('T115')">Round</button>
<button type="button" onclick="showTop('T345')">Rectangular</button>
</ul>
</div>
<canvas id="renderCanvas"></canvas>
</div>
</div>
</div>
<script>
if (BABYLON.Engine.isSupported()) {
var myNewScene = null;
var canvas = document.getElementById("renderCanvas");
var engine = new BABYLON.Engine(canvas, true);
BABYLON.SceneLoader.Load("", "test.babylon", engine, function (newScene) {
myNewScene = newScene;
var meshT115 = newScene.getMeshByName("T115").visibility = 0;
var mesh510 = newScene.getMeshByName("510").visibility = 1;
var meshT345 = newScene.getMeshByName("T345").visibility = 1;
var mesh350 = newScene.getMeshByName("350").visibility = 0;
var myBaseMesh = newScene.getMeshByName("510");
var materialMyMesh = new BABYLON.StandardMaterial("texture1", newScene);
materialMyMesh.diffuseTexture = new BABYLON.Texture("assets/images/stain/Natural.jpg", newScene);
materialMyMesh.specularPower = 50;
myBaseMesh.material = materialMyMesh;
var myTopMesh = newScene.getMeshByName("T345");
var materialMyMesh = new BABYLON.StandardMaterial("texture2", newScene);
materialMyMesh.diffuseTexture = new BABYLON.Texture("assets/images/stain/Natural.jpg", newScene);
materialMyMesh.specularPower = 50;
myTopMesh.material = materialMyMesh;
// Wait for textures and shaders to be ready
newScene.executeWhenReady(function () {
// Attach camera to canvas inputs
var myCamera = new BABYLON.ArcRotateCamera("ArcRotateCamera", 1.2, 1.2, 5, new BABYLON.Vector3(0, 0.1, 0.1), newScene);
myCamera.wheelPrecision = 10;
var light0 = new BABYLON.HemisphericLight("Hemi0", new BABYLON.Vector3(0, 50, 0), newScene);
light0.diffuse = new BABYLON.Color3(1, 1, 1);
light0.specular = new BABYLON.Color3(1, 1, 1);
light0.groundColor = new BABYLON.Color3(.5, .5, .5);
newScene.activeCamera = myCamera;
newScene.activeCamera.attachControl(canvas);
// Once the scene is loaded, just register a render loop to render it
engine.runRenderLoop(function() {
newScene.render();
});
});
}, function (progress) {
// To do: give progress feedback to user
});
}
function showTop (x) {
myNewScene.getMeshById("myTopMesh").visibility = 0;
myNewScene.getMeshById(x).visibility = 1;
}
</script>
</body>
</html>
However, all I get is an Error.
Uncaught TypeError: undefined is not a function
showTop 3d.php::88
onclick 3d.php::88
Line 88 is:
myNewScene.getMeshById(x).visibility = 1;
My question is, if I am declaring myNewScene as a global variable and then assigning it within my scene creation why does my browser think it should be a function?
Thanks.
change this:
if (BABYLON.Engine.isSupported()) {
var myNewScene = null;
var canvas = document.getElementById("renderCanvas");
var engine = new BABYLON.Engine(canvas, true);
to something like this:
var myNewScene, canvas, engine;
if (BABYLON.Engine.isSupported()) {
myNewScene = null;
canvas = document.getElementById("renderCanvas");
engine = new BABYLON.Engine(canvas, true);
Related
Using Mxgraph I am creating a tool where I have only Custom icons.
I need to add names under custom Icon in toolbox and also while icon drag and drop the name also should come below the icon in the container.
Here is the below code you can use for reference
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
mxBasePath = 'src';
</script>
<script type="text/javascript" src="src/js/mxClient.js"></script>
<script type="text/javascript">
function main()
{
var tbContainer = document.getElementById('tbContainer');
var toolbar = new mxToolbar(tbContainer);
toolbar.enabled = false
container = document.getElementById('container');
if (mxClient.IS_QUIRKS)
{
document.body.style.overflow = 'hidden';
new mxDivResizer(tbContainer);
new mxDivResizer(container);
}
var model = new mxGraphModel();
var graph = new mxGraph(container, model);
graph.dropEnabled = true;
var parent = graph.getDefaultParent();
var style = new Object();
style[mxConstants.STYLE_SHAPE] = mxConstants.SHAPE_IMAGE;
style[mxConstants.STYLE_PERIMETER] = mxPerimeter.RectanglePerimeter;
style[mxConstants.STYLE_IMAGE] = 'images/svg/start.svg';
style[mxConstants.STYLE_FONTCOLOR] = '#FFFFFF';
graph.getStylesheet().putCellStyle('imagestart', style);
mxDragSource.prototype.getDropTarget = function(graph, x, y)
{
var cell = graph.getCellAt(x, y);
if (!graph.isValidDropTarget(cell))
{
cell = null;
}
return cell;
};
graph.setConnectable(true);
graph.setMultigraph(false);
var keyHandler = new mxKeyHandler(graph);
var rubberband = new mxRubberband(graph);
var addVertex = function(icon, w, h, style)
{
var vertex = new mxCell(null, new mxGeometry(0, 0, w, h), style);
vertex.setVertex(true);
//vertex.setText("Icon name");
addToolbarItem(graph, toolbar, vertex, icon);
};
toolbar.addLine();
addVertex('images/rectangle.gif', 100, 40, '');
addVertex('images/sample.png', 50, 50, 'imagestart');
toolbar.addLine();
}
function addToolbarItem(graph, toolbar, prototype, image)
{
var funct = function(graph, evt, cell)
{
graph.stopEditing(false);
var pt = graph.getPointForEvent(evt);
var vertex = graph.getModel().cloneCell(prototype);
vertex.geometry.x = pt.x;
vertex.geometry.y = pt.y;
graph.setSelectionCells(graph.importCells([vertex], 0, 0, cell));
}
var img = toolbar.addMode(null, image, funct);
mxUtils.makeDraggable(img, graph, funct);
}
</script>
</head>
<body onload="main()">
<div id="container" style="position:absolute;overflow:hidden;left:0px;top:26px;right:150px;bottom:0px;background:url('src/images/grid.gif');"></div>
<div id="tbContainer" style="position:absolute; overflow:hidden;padding:2px; left:1400px;top:26px; width:24px; bottom:0px;">
</div>
</body>
</html>
Here I have added an image where I have added red mark. I need to add text in that place.
vertex.setText("Icon name");
Help me to figure out this issues
I found the solution for this. This may be useful for some others.
Its very simple.
while addToolbarItem we just need to specify the name of the tool icon like this
var img = toolbar.addMode("Start", image, funct);
and on drag and drop we need to pass the text like below
var vertex = new mxCell("start", new mxGeometry(0, 0, w, h), style);
For giving style for the text you can add the style like the below
style[mxConstants.STYLE_VERTICAL_LABEL_POSITION] = 'top';
style[mxConstants.STYLE_VERTICAL_ALIGN] = 'bottom';
style[mxConstants.STYLE_FONTSIZE] = '18';
//style[mxConstants.STYLE_FONTSTYLE] = 1;
style[mxConstants.STYLE_FONTCOLOR] = '#333';
style[mxConstants.STYLE_FONTFAMILY] = 'Lato-Regular';
style['fontWeight'] = 'regular';
graph.getStylesheet().putCellStyle('imagestart', style);
With spending few hours I got this solutions. Please correct me if I am doing any wrong
I keep studing Three.js. I charge a 3D model with the function JSONLoader and when I want to put it a shadow, it doesn't appear and I don't know why because I think I do all the steps:
1- Active the the ShadowMap.
2- I have lights.
3- The plane has recieveShadow = true;
4- The 3D model has castShadow = true;
The completily code (now it's working):
<html><head>
<title>Ejemplo 9 Three.js</title>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"/> <!--320-->
<script type = 'text/javascript' src = "plugins/jquery/jquery.js"></script>
<script type = 'text/javascript' src = "plugins/bootstrap/bootstrap.js"></script>
<script type = 'text/javascript' src = "plugins/three.js-master/build/three.js"></script>
<script type = 'text/javascript' src = "plugins/dat.gui.js/dat.gui.js"></script>
<script type = 'text/javascript' src = "plugins/threex.windowresize-master/threex.windowresize.js"></script>
<script type = 'text/javascript' src = "plugins/threex.keyboardstate-master/threex.keyboardstate.js"></script>
<script type = 'text/javascript' src = "plugins/orbitcontrols/OrbitControls.js"></script>
<script type = 'text/javascript' src = "plugins/ColladaLoader/ColladaLoader.js"></script>
<link rel = "stylesheet" type = "text/css" href = "css/bootstrap.css">
<style>
body{
margin: 0;
padding: 0;
overflow: hidden;
}
#renderer{
overflow: hidden
}
.container-fluid{
margin: 0;
padding: 0;
}
.col-md-12{
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div class="container-fluid">
<div class="col-md-12">
<ul>
<li>Up, Down, Left, Right-> Move cube. </li>
<li>Z & X -> Rotate cube. </li>
<li>WASD -> Scale cube.</li>
</ul>
<div id="renderer">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
var renderer;
var controls;
var scene;
var keyboard;
var material;
var plane_texture;
var grass;
var geometry_cube;
var cube_material;
var cube_texture;
var cube;
//Modelo 3D .js
var model3D;
var materials_modelo3D; //materiales
var final_model; //vértices + materiales
//Modelo 3D .dae
var model3Ddae;
var final_modeldae;
var speed;
var space;
var time;
var width;
var height;
var fov;
var aspect;
var near;
var far;
var camera;
var light;
var ambient_light;
var solar_light;
start();
function start(){
renderer = new THREE.WebGLRenderer({antialias:true});
renderer.shadowMap.enabled= true;
width = window.innerWidth-10;
height = window.innerHeight-10;
//alert("ancho: " + width + ", alto:" + height);
renderer.setSize(width, height);
$("#renderer").append(renderer.domElement);
scene = new THREE.Scene();
keyboard = new THREEx.KeyboardState();
model3D = new THREE.JSONLoader(); //vertices
model3Ddae = new THREE.ColladaLoader();
fov = 45; //angle
aspect = width/height;
near = 0.1;
far = 1000;
camera = new THREE.PerspectiveCamera (fov, aspect, near, far);
THREEx.WindowResize(renderer, camera);
var color = new THREE.Color("rgb(250, 250, 250)");
renderer.setClearColor(new THREE.Color(color));
camera.position.z= 20;
camera.position.y= 10;
scene.add(camera);
controls = new THREE.OrbitControls(camera, renderer.domElement);
plane_texture = new THREE.TextureLoader().load("texturas/cesped.jpg");
cube_texture = new THREE.TextureLoader().load("texturas/muro.jpg");
crear_plano();
model3D.load("models/layers260a.js", functionAddModel);
// model3Ddae.load("models/rifle.dae" , functionAddModelDae);
// cube();
makeLight();
var ejesAyuda = new THREE.AxesHelper(20); //son los ejes de ayuda creo
scene.add(ejesAyuda);
renderer.render(scene, camera);
}
function crear_plano(){
geometria_plano = new THREE.PlaneGeometry(100, 100, 10, 10);
plane_texture.wrapS = plane_texture.wrapT = THREE.RepeatWrapping; // para repetir la textura a lo largo y a lo width
plane_texture.repeat.set(10, 10); // tablero de 10 x 10
//material y agregado de textura
material = new THREE.MeshLambertMaterial({map: plane_texture, side: THREE.DoubleSide});
grass = new THREE.Mesh(geometria_plano, material);
//grass.rotation.y=-0.5;
grass.rotation.x=Math.PI/2;
grass.receiveShadow=true;
scene.add(grass);
}
function functionAddModel(geometry){
imagen = new THREE.TextureLoader().load("models/mario.jpg");
materials_modelo3D = new THREE.MeshLambertMaterial({map: imagen});
final_model = new THREE.Mesh(geometry, materials_modelo3D);
scene.add(final_model);
final_model.scale.set(10, 10, 10);
final_model.position.set(10, 13, 10);
final_model.rotation.y = Math.PI;
final_model.castShadow = true;
final_model.receiveShadow = false;
animation();
}
function functionAddModelDae(infodae){
final_modeldae = infodae.scene;
final_modeldae.position.set(20, 5, 10);
final_modeldae.scale.x = final_modeldae.scale.y = final_modeldae.scale.z =.2;
// final_modeldae.rotation.y = Math.PI;
scene.add(final_modeldae);
}
function animation(){
requestAnimationFrame(animation);
render_modelo();
var objMov = final_model;
speed = 100;
time = 0.001;
space = speed * time;
if(keyboard.pressed("up")){ //tecla flecha arriba
objMov.position.z+=space;
}else if(keyboard.pressed("down")){
objMov.position.z-=space;
}else if(keyboard.pressed("right")){
objMov.position.x+=space;
}else if(keyboard.pressed("left")){
objMov.position.x-=space;
}else if(keyboard.pressed("z")){
objMov.rotation.x+=space;
}else if(keyboard.pressed("x")){
objMov.rotation.y+=space;
}else if(keyboard.pressed("w")){
objMov.scale.y+=space;
}else if(keyboard.pressed("a")){
objMov.scale.x-=space;
}else if(keyboard.pressed("s")){
objMov.scale.y-=space;
}else if(keyboard.pressed("d")){
objMov.scale.x+=space;
}
controls.target.set(objMov.position.x, objMov.position.y, objMov.position.z);
}
function render_modelo(){
controls.update();
renderer.render(scene, camera);
}
function cube(){
geometry_cube = new THREE.CubeGeometry(10, 10, 10);
cube_material = new THREE.MeshLambertMaterial({map:cube_texture, side:THREE.DoubleSide, wireframe: false});
cube = new THREE.Mesh(geometry_cube, cube_material);
cube.position.x= -4;
cube.position.y = 6;
cube.position.z = 0;
cube.castShadow = true;
scene.add(cube);
}
function makeLight(){
light = new THREE.PointLight(0xffffff);
light.position.set(-100,200,100);
scene.add(light);
ambient_light = new THREE.AmbientLight(0x000000);
scene.add(ambient_light);
solar_light = new THREE.DirectionalLight();
solar_light.position.set(500, 500, -500);
solar_light.castShadow = true;
solar_light.intensity = 1.3;
solar_light.shadow.mapSize.width = 1024;
solar_light.shadow.mapSize.height = 1024;
solar_light.shadow.camera.near = 250;
solar_light.shadow.camera.far = 1000;
intensidad=50;
solar_light.shadowCameraLeft = -intensidad;
solar_light.shadowCameraRight = intensidad;
solar_light.shadowCameraTop = intensidad;
solar_light.shadowCameraBottom = -intensidad;
scene.add(solar_light);
var helper = new THREE.CameraHelper( light.shadow.camera );
var helper2 = new THREE.CameraHelper(solar_light.shadow.camera);
scene.add(helper);
scene.add(helper2);
}
});
</script>
</body>
</html>
The scene:
Thanks for you help, as always :)
Your "grass" material is a MeshBasicMaterial. As the name implies, it is purely basic, and does not respond to light sources.
Interestingly, MeshBsicMaterial can cast shadows,
but cannot receive them.
(https://github.com/mrdoob/three.js/issues/8116#issuecomment-183459078).
Change your grass material to MeshLambertMaterial, and the shadows will appear.
I'm trying to clone a shape (square) every time I click a button. I also want to be able to drag the shapes around the canvas. This is my current code:
-inline script
var stage;
var update = true;
var count = 1;
function init(){
stage = new createjs.Stage('myCanvas');
var rect = new createjs.Shape();
rect.graphics.beginFill('#000000').drawRect(0,0,50,50);
rect.name = "rect_" + count;
count++;
var rectName = rect.name
var dragger = new createjs.Container(rectName);
dragger.x = dragger.y = 100;
dragger.addChild(rect);
stage.addChild(dragger);
dragger.on("pressmove",function(evt) {
// currentTarget will be the container that the event listener was added to:
evt.currentTarget.x = evt.stageX;
evt.currentTarget.y = evt.stageY;
// make sure to redraw the stage to show the change:
stage.update();
});
stage.update();
}
$(function(){
$('button').click(function(){
console.log('fire!');
init();
})
})
-file.html
<body onload='init()'>
<canvas id='myCanvas' width='500' height='500'></canvas>
<button class='makeBox'>New Box!</button>
</body>
As you can see I can create a shape and drag it around. But when I click the button it refreshes the shape instead of cloning it. I read this post but I was still a little confused on how to implement cloning.
duplicating objects with easeljs
Can someone please point me in the right direction. If you want bonus points make it so the shapes don't overlap each other. I would appreciate it so much :)
Please have a look at this running code snippet. Hope it will help you a bit.
var stage;
var update = true;
var count = 1;
var rect = null;
var draggerCord = 0;
function init(refRect){
if(refRect)
{
rect = refRect;
}
else
{
stage = new createjs.Stage('myCanvas');
rect = new createjs.Shape();
}
rect.graphics.beginFill('#000000').drawRect(0,0,50,50);
rect.name = "rect_" + count;
count++;
var rectName = rect.name
var dragger = new createjs.Container(rectName);
dragger.x = dragger.y = 100 + draggerCord;
draggerCord +=50;
if(draggerCord > 500)
draggerCord = 100;
dragger.addChild(rect);
stage.addChild(dragger);
dragger.on("pressmove",function(evt) {
// currentTarget will be the container that the event listener was added to:
evt.currentTarget.x = evt.stageX;
evt.currentTarget.y = evt.stageY;
// make sure to redraw the stage to show the change:
stage.update();
});
stage.update();
}
function cloneRect(){
var rectClone = rect.clone();
init(rectClone);
}
$(function(){
$('button').click(function(){
cloneRect();
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://code.createjs.com/createjs-2015.11.26.min.js"></script>
<body onload='init()'>
<canvas id='myCanvas' width='500' height='500'></canvas>
<button class='makeBox'>New Box!</button>
</body>
I have the following files( using last PIXI.js version):
index.html
<!DOCTYPE HTML>
<html>
<head>
<title>pixi.js example 1</title>
<style>
body {
margin: 0;
padding: 0;
background-color: #000000;
width:100%;
height:100%;
}
canvas {
display:block;
}
</style>
<script src="js/pixi.js"></script>
<script src="js/XALUI/XALUI.js"></script>
<script src="js/XALUI/Button.js"></script>
</head>
<body>
<script>
// create an new instance of a pixi stage
var stage = new PIXI.Stage(0x66FF99);
// create a renderer instance
var renderer = PIXI.autoDetectRenderer(window.innerWidth, window.innerHeight);
// add the renderer view element to the DOM
document.body.appendChild(renderer.view);
requestAnimFrame( animate );
// create a texture from an image path
var texture = PIXI.Texture.fromImage("bunny.png");
// XALUI
var button = new XALUI.Button(texture);
stage.addChild(button);
function animate() {
button.position.x = button.position.x + 20;
// render the stage
renderer.render(stage);
requestAnimFrame( animate );
}
</script>
</body>
</html>
js/XALUI/Button.js
XALUI.Button = function(texture) {
PIXI.DisplayObject.call(this);
this._button = new PIXI.Sprite(texture);
}
XALUI.Button.prototype = Object.create(PIXI.DisplayObject.prototype);
XALUI.Button.prototype.constructor = XALUI.Button;
XALUI.Button.prototype._renderWebGL = function(renderSession) {
this._button._renderWebGL(renderSession);
}
XALUI.Button.prototype._renderCanvas = function(renderSession) {
this._button._renderCanvas(renderSession);
};
How can I move my button to another position or to an another initial position? I have tried setting the position.x:
var button = new XALUI.Button(texture);
button.position.x = 100;
And also tried to set the position of the sprite:
this._button = new PIXI.Sprite(texture);
this._button.position.x = 100;
But it doesn't work. Please help.
The problem lies in that you're attaching and moving XALUI.Button instead of the inner PIXI.Sprite. Setting the position on the inner sprite (this._button.position.x) would only work if you had added that PIXI.Sprite to the stage. Since DisplayObjects do not contain multiple DisplayObjects, the stage has no reference to the actual sprite. There are a couple of ways to fix this. First, you could inherit from PIXI.Sprite
XALUI.Button = function(texture) {
PIXI.Sprite.call(this, texture);
};
XALUI.Button.prototype = Object.create(PIXI.Sprite.prototype);
XALUI.Button.prototype.constructor = XALUI.Button;
Or to have it inherit from DisplayObjectContainer in the same manner as above but that implies a button will hold multiple graphical objects so do what works best for you. Here's a working example of the first approach.
var XALUI = {};
// Inherits from PIXI.Sprite
XALUI.Button = function(texture) {
PIXI.Sprite.call(this, texture);
};
XALUI.Button.prototype = Object.create(PIXI.Sprite.prototype);
XALUI.Button.prototype.constructor = XALUI.Button;
// Prepare the stage
var stage = new PIXI.Stage(0x66FF99);
var renderer = PIXI.autoDetectRenderer(window.innerWidth, window.innerHeight);
var texture = PIXI.Texture.fromImage("http://www.goodboydigital.com/pixijs/examples/1/bunny.png");
var button = new XALUI.Button(texture);
document.body.appendChild(renderer.view);
requestAnimationFrame(animate);
stage.addChild(button);
// Animate the button
function animate() {
button.position.x = button.position.x + 5;
if (button.position.x > window.innerWidth + button.width) {
button.position.x = -button.width;
}
renderer.render(stage);
requestAnimationFrame(animate);
}
<script src="https://cdn.rawgit.com/GoodBoyDigital/pixi.js/v2.0.0/bin/pixi.js"></script>
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