Babylon js Rotate After Physics Imposter - javascript

Well, been on html 5 apis and about two days ago stumbled on babylon js for 3d on html 5 using webgl; but the issue is that it is a new technology and not much work has been done with it and also not much videos tutorials as expected on it. So with three days using the technology, I have been able to try a little with the physics engine.
I want to rotate box 2 after adding the physics state but I can't do that. I can only rotate the object before adding the physics state.
I know in modern games, even objects on air can rotate and yet fall due to gravity. What can I do about this, will I have to remove the physics property, rotate object and re rotate the object. Below is my code:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
html, body {
overflow: hidden;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
#renderCanvas {
width: 100%;
height: 100%;
touch-action: none;
}
</style>
<script src="../js/babylon.2.0.js"></script>
<script src="../js/hand-1.3.8.js"></script>
<script src="../js/cannon.js"></script> <!-- optional physics engine -->
<!-- <script src="../js/Oimo.js"></script> New physics engine -->
</head>
<body>
<canvas id="renderCanvas"></canvas>
<script type="text/javascript">
// Get the canvas element from our HTML below
var canvas = document.querySelector("#renderCanvas");
// Load the BABYLON 3D engine
var MyScene = function(){
console.log("MyScene Activated: Trying to test Object Oriented Javascript With Babylon js")
};
MyScene.prototype.engine = new BABYLON.Engine(canvas, true);
MyScene.prototype.createScene = function(){
// Now create a basic Babylon Scene object
var scene = new BABYLON.Scene(this.engine);
scene.enablePhysics(null,new BABYLON.CannonJSPlugin());
scene.setGravity(new BABYLON.Vector3(0,-10,0));
// Change the scene background color to green.
scene.clearColor = new BABYLON.Color3(200, 1, 0.3);
var camera = new BABYLON.ArcRotateCamera("camera",1,1.4,53,new BABYLON.Vector3(0,0,0),scene);
// This attaches the camera to the canvas
camera.attachControl(canvas, false);
// This creates a light, aiming 0,1,0 - to the sky.
var light = new BABYLON.PointLight("light1", new BABYLON.Vector3(0, 0, 10), scene);
// Dim the light a small amount
light.intensity = .5;
MyScene.prototype.ball = BABYLON.Mesh.CreateSphere("sphere1", 16, 2, scene);
MyScene.prototype.ball.position.y = 10;
MyScene.prototype.ball.setPhysicsState({ impostor : BABYLON.PhysicsEngine.BoxImpostor, friction : 0.5 , mass: 10, restitution : 0.7});
MyScene.prototype.box1 = BABYLON.Mesh.CreateBox("box1",3,scene);
MyScene.prototype.box1.position.x = 3;
MyScene.prototype.box1.scaling.x = 1;
MyScene.prototype.box1.position.y = -6;
MyScene.prototype.box1.setPhysicsState({ impostor : BABYLON.PhysicsEngine.BoxImpostor, friction : 0.5 , mass: 10, restitution : 0.7});
MyScene.prototype.box2 = BABYLON.Mesh.CreateBox("box2",3,scene);
MyScene.prototype.box2.position.x = 6;
MyScene.prototype.box2.position.y = 10;
MyScene.prototype.box2.setPhysicsState({ impostor : BABYLON.PhysicsEngine.BoxImpostor, friction : 0.5 , mass: 10, restitution : 0.7});
MyScene.prototype.box3 = BABYLON.Mesh.CreateBox("box3",3,scene);
MyScene.prototype.box3.position.x = 1;
MyScene.prototype.box3.setPhysicsState({ impostor : BABYLON.PhysicsEngine.BoxImpostor, friction : 0.5 , mass: 10, restitution : 0.7});
MyScene.prototype.ground = BABYLON.Mesh.CreateBox("box",50,scene);
MyScene.prototype.ground.position.y = -10;
MyScene.prototype.ground.scaling.y = 0.1;
MyScene.prototype.ground.setPhysicsState({ impostor : BABYLON.PhysicsEngine.BoxImpostor, friction : 0.5 , mass: 0, restitution : 0.7});
// Leave this function
return scene;
};
MyScene.prototype.getEngine = function(){
return this.engine;
};
MyScene.prototype.scale = function(){
counter = 0;
while(counter <= 10){
MyScene.prototype.box2.rotate(BABYLON.Axis.X,counter,BABYLON.Space.LOCAL);
MyScene.prototype.box2.rotate(BABYLON.Axis.Y,counter,BABYLON.Space.LOCAL);
MyScene.prototype.box2.rotate(BABYLON.Axis.Z,counter,BABYLON.Space.LOCAL);
++counter;
}
}
MyScene.prototype.pos = function(){
this.box1.position.x += 0.2;
this.box1.scaling.x += 0.2;
this.box2.position.x += 0.2;
this.box2.scaling.x += 0.2;
this.box3.position.x += 0.2;
this.box3.scaling.x += 0.2;
};
var Myscene = new MyScene();
var scene = Myscene.createScene();
// Register a render loop to repeatedly render the scene
Myscene.getEngine().runRenderLoop(function () {
scene.render();
Myscene.scale();
});
// Watch for browser/canvas resize events
window.addEventListener("resize", function () {
Myscene.getEngine().resize();
});
</script>
</body>
</html>

when a mesh is under the control of the physics engine, you have to use this specific code after applying rotation changes: mesh.updatePhysicsBodyPosition()
This function will keep the physics simulation updated

Related

Limit dragged line to an arc / radius of a given length

I'm currently using Phaser 3, although my question isn't technically restricted to that framework, as it's more of a general JS/canvas/maths question, but:
I have a line drawn with graphics(). It’s anchored at one end, and the other end is draggable. I made a quick demo and so far, so good - you can see what I have already on CodePen.
Dragging the marker around and redrawing the line is no problem, but what I’d like is for that line to have a maximum length of 100, so even if you’re still dragging beyond that point, the line would still follow the mouse, but not get any longer than 100. Dragging inside that maximum radius, the line would shrink as normal.
I’ve put together a visual that hopefully explains it:
The issue is that I suspect this is VERY MATHS and I am very, very weak with maths. Could anyone explain like I’m five what I need to do to my code to achieve this?
Edit: Adding code in a snippet here, as requested:
var config = {
type: Phaser.AUTO,
width: 800,
height: 400,
backgroundColor: '#2d2d2d',
parent: 'phaser-example',
scene: {
preload: preload,
create: create,
update: update
}
};
var path;
var curve;
var graphics;
var game = new Phaser.Game(config);
function preload() {
this.load.spritesheet('dragcircle', 'https://labs.phaser.io/assets/sprites/dragcircle.png', { frameWidth: 16 });
}
function create() {
graphics = this.add.graphics();
path = { t: 0, vec: new Phaser.Math.Vector2() };
curve = new Phaser.Curves.Line([ 400, 390, 300, 230 ]);
var point0 = this.add.image(curve.p0.x, curve.p0.y, 'dragcircle', 0);
var point1 = this.add.image(curve.p1.x, curve.p1.y, 'dragcircle', 0).setInteractive();
point1.setData('vector', curve.p1);
this.input.setDraggable(point1);
this.input.on('drag', function (pointer, gameObject, dragX, dragY) {
gameObject.x = dragX;
gameObject.y = dragY;
gameObject.data.get('vector').set(dragX, dragY);
});
this.input.on('dragend', function (pointer, gameObject) {
let distance = Phaser.Math.Distance.Between(curve.p0.x, curve.p0.y, curve.p1.x, curve.p1.y);
console.log(distance);
});
}
function update() {
graphics.clear();
graphics.lineStyle(2, 0xffffff, 1);
curve.draw(graphics);
curve.getPoint(path.t, path.vec);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/3.55.2/phaser.min.js"></script>
You are right, you would need some math, but phaser has many helper functions, that will do the heavy lifting.
The main idea is, of this solution is
define a maxLength
get the the new point on drag, and create a real Phaser Vector2
here is some math is needed, to create the vector, just calculate destination point minus origin point
new Phaser.Math.Vector2(pointer.x - point0.x, pointer.y - point0.y) (origin point being the starting point of the desired vector, and destination point being the mouse pointer)
calculate the length of the created vector and compare it with the maxLength
if too long adjust the vector, with the handy function setLength (link to the documentation, this is where you would have needed math, but thankfully Phaser does it for us)
set the new coordinates for point1 and the curve endpoint
Here a quick demo (based on your code):
var config = {
type: Phaser.AUTO,
width: 500,
height: 170,
scene: {
preload: preload,
create: create,
update: update
}
};
var curve;
var graphics;
var game = new Phaser.Game(config);
function preload() {
this.load.spritesheet('dragcircle', 'https://labs.phaser.io/assets/sprites/dragcircle.png', { frameWidth: 16 });
}
function create() {
graphics = this.add.graphics();
curve = new Phaser.Curves.Line([ config.width/2, config.height - 20, config.width/2, 10 ]);
// define a length, could be a global constant
let maxLength = curve.p0.y - curve.p1.y;
var point0 = this.add.image(curve.p0.x, curve.p0.y, 'dragcircle', 0);
var point1 = this.add.image(curve.p1.x, curve.p1.y, 'dragcircle', 0).setInteractive();
this.input.setDraggable(point1);
// Just add for Debug Info
this.add.circle(curve.p0.x, curve.p0.y, maxLength)
.setStrokeStyle(1, 0xffffff, .5)
this.input.on('drag', function (pointer) {
let vector = new Phaser.Math.Vector2(pointer.x - point0.x, pointer.y - point0.y);
let distance = Phaser.Math.Distance.Between( point0.x, point0.y, pointer.x, pointer.y);
if(distance > maxLength){
vector.setLength(maxLength);
}
point1.x = point0.x + vector.x;
point1.y = point0.y + vector.y;
curve.p1.x = point1.x;
curve.p1.y = point1.y;
});
// NOT REALLY NEEDED
/*this.input.on('dragend', function (pointer, gameObject) {
let distance = Phaser.Math.Distance.Between(curve.p0.x, curve.p0.y, curve.p1.x, curve.p1.y);
console.log(distance);
});*/
}
function update() {
graphics.clear();
graphics.lineStyle(2, 0xffffff, 1);
curve.draw(graphics);
}
<script src="https://cdn.jsdelivr.net/npm/phaser#3.55.2/dist/phaser.js"></script>
Optional - Code Version using Phaser.GameObjects.Line:
This uses less code, and thanks to the Line GameObject (link to Documentation), you can directly use the vector to update the line, and also don't need the update function, graphics and so.
const config = {
type: Phaser.CANVAS,
width: 500,
height: 160,
scene: {
create
}
};
const game = new Phaser.Game(config);
const MAX_LINE_LENGTH = 100;
function create() {
let points = [ {x: config.width/2, y: config.height - 20}, {x: config.width/2, y: config.height - 120} ];
let point0 = this.add.circle(points[0].x, points[0].y, 6)
.setStrokeStyle(4, 0xff0000);
let point1 = this.add.circle(points[1].x, points[1].y, 6)
.setStrokeStyle(4, 0xff0000)
.setInteractive();
this.input.setDraggable(point1);
// Just add for Debug Info
this.add.circle(point0.x, point0.y, MAX_LINE_LENGTH)
.setStrokeStyle(1, 0xffffff, .5);
let line = this.add.line(points[0].x, points[0].y, 0, 0, 0, -100, 0x00ff00)
.setOrigin(0);
this.input.on('drag', function (pointer) {
let vector = new Phaser.Math.Vector2(pointer.x - point0.x, pointer.y - point0.y);
let distance = Phaser.Math.Distance.Between( point0.x, point0.y, pointer.x, pointer.y);
if(distance > MAX_LINE_LENGTH){
vector.setLength(MAX_LINE_LENGTH);
}
point1.x = point0.x + vector.x;
point1.y = point0.y + vector.y;
line.setTo(0, 0, vector.x, vector.y);
});
}
<script src="//cdn.jsdelivr.net/npm/phaser#3.55.2/dist/phaser.js"></script>

Three.js Objects not showing, there is only a black screen shown

I've been having this similar issue with a few of my other three.js codes as well. I set up the js within html but the objects are not showing up. There's just a black screen showing up when I run the file.
The file is supposed to show rain drops falling off the sky when it is run.
I used atom to build it. I tried html preview on atom, atom live server internet explorer chrome and they all showed the same black screen when i tried running it.
<!DOCTYPE html>
<html>
<head>
<meta charset=UTF-8 />
<link rel="stylesheet" type="text/css" href="styles.css" />
<title>RAIN ON ME BABY</title>
</head>
<body>
<script src="js/three.min.js"></script>
<script>
let scene,camera, renderer, cloudParticles = [], flash, rain, rainGeo, rainCount = 15000;
function init() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(60,window.innerWidth / window.innerHeight, 1, 1000);
camera.position.z = 1;
camera.rotation.x = 1.16;
camera.rotation.y = -0.12;
camera.rotation.z = 0.27;
ambient = new THREE.AmbientLight(0x555555);
scene.add(ambient);
directionalLight = new THREE.DirectionalLight(0xffeedd);
directionalLight.position.set(0,0,1);
scene.add(directionalLight);
flash = new THREE.PointLight(0x062d89, 30, 500 ,1.7);
flash.position.set(200,300,100);
scene.add(flash);
renderer = new THREE.WebGLRenderer();
scene.fog = new THREE.FogExp2(0x11111f, 0.002);
renderer.setClearColor(scene.fog.color);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
rainGeo = new THREE.Geometry();
for(let i=0;i<rainCount;i++) {
rainDrop = new THREE.Vector3(
Math.random() * 400 -200,
Math.random() * 500 - 250,
Math.random() * 400 - 200
);
rainDrop.velocity = {};
rainDrop.velocity = 0;
rainGeo.vertices.push(rainDrop);
}
rainMaterial = new THREE.PointsMaterial({
color: 0xaaaaaa,
size: 0.1,
transparent: true
});
rain = new THREE.Points(rainGeo,rainMaterial);
scene.add(rain);
let loader = new THREE.TextureLoader();
loader.load("smoke.png", function(texture){
cloudGeo = new THREE.PlaneBufferGeometry(500,500);
cloudMaterial = new THREE.MeshLambertMaterial({
map: texture,
transparent: true
});
for(let p=0; p<25; p++) {
let cloud = new THREE.Mesh(cloudGeo,cloudMaterial);
cloud.position.set(
Math.random()*800 -400,
500,
Math.random()*500 - 450
);
cloud.rotation.x = 1.16;
cloud.rotation.y = -0.12;
cloud.rotation.z = Math.random()*360;
cloud.material.opacity = 0.6;
cloudParticles.push(cloud);
scene.add(cloud);
}
animate();
});
}
function animate() {
cloudParticles.forEach(p => {
p.rotation.z -=0.002;
});
rainGeo.vertices.forEach(p => {
p.velocity -= 0.1 + Math.random() * 0.1;
p.y += p.velocity;
if (p.y < -200) {
p.y = 200;
p.velocity = 0;
}
});
rainGeo.verticesNeedUpdate = true;
rain.rotation.y +=0.002;
if(Math.random() > 0.93 || flash.power > 100) {
if(flash.power < 100)
flash.position.set(
Math.random()*400,
300 + Math.random() *200,
100
);
flash.power = 50 + Math.random() * 500;
}
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
init();
</script>
</body>
</html>
Your issue is actually a duplicate of: https://stackoverflow.com/a/57114890/5250847
With R016, it's not possible to create THREE.Points with THREE.Geometry. This is already fixed in dev and eventually with the next release R107 at the end of July.
I've copied your code to the following fiddle and replaced the build file with the current dev version which fixes the issue.
https://jsfiddle.net/76tw2jL0/
BTW: The best fix is actually the usage of THREE.BufferGeometry.

Replace 3d model (json)

I found an example online and in this example that shows a 3D model (a Ferris wheel) placed on a parking lot with a Google Street View Panorama as the background.
Now I want to replace the Ferris wheel with another 3d object — an asteroid — that I download as a 3DS and OBJ. file. I converted the 3DS file to JSON through Blender but when I replace the file it just shows a blank screen.
How can I do it? Here is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Street View Overlay - EINA</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
body {
margin: 0px;
overflow: hidden;
}
p {
font-family:sans-serif;
font-size:11px;
font-weight:bold;
color:#111111;
}
</style>
</head>
<body>
<div id="streetviewpano" style="position: absolute; top:0; bottom:0; left:0; right:0; z-index: 0">
</div>
<div id="container" style="position: absolute; top:0; bottom:100px; left: 0; right: 0; z-index: 100;">
</div>
<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false"></script>
<script src="lib/jquery-2.0.3.js"></script>
<script src="lib/jquery.mousewheel.js"></script>
<script src="lib/three.min.js"></script>
<script src="lib/Detector.js"></script>
<script src="src/streetviewoverlay.js"></script>
<script>
var METERS2DEGREES = 0.0000125;
var objectPosition = [48.804828,2.1203071];
function hackMapProjection(lat, lon, originLat, originLon) {
var lonCorrection = 1.5;
var rMajor = 6378137.0;
function lonToX(lon) {
return rMajor * (lon * Math.PI / 180);
}
function latToY(lat) {
if (lat === 0) {
return 0;
} else {
return rMajor * Math.log(Math.tan(Math.PI / 4 + (lat * Math.PI / 180) / 2));
}
}
var x = lonToX(lon - originLon) / lonCorrection;
var y = latToY(lat - originLat);
return {'x': x, 'y': y};
}
function latLon2ThreeMeters(lat, lon) {
var xy = hackMapProjection(lat, lon, objectPosition[0], objectPosition[1]);
return {'x': xy.x, 'y': 0, 'z': -xy.y};
}
var jsonLoader = new THREE.JSONLoader();
jsonLoader.load( "model3d/wheel.js", loadWheel );
function loadWheel(geometry, materials) {
var mesh;
mesh = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));
meshPos = latLon2ThreeMeters(objectPosition[0], objectPosition[1]);
mesh.geometry.computeBoundingBox();
var xsize = mesh.geometry.boundingBox.max.x - mesh.geometry.boundingBox.min.x;
var ysize = mesh.geometry.boundingBox.max.y - mesh.geometry.boundingBox.min.y;
var zsize = mesh.geometry.boundingBox.max.z - mesh.geometry.boundingBox.min.z;
var desiredXSize = 10;
var desiredYSize = 10;
var desiredZSize = 10;
mesh.scale.x = desiredXSize / xsize;
mesh.scale.y = desiredYSize / ysize;
mesh.scale.z = desiredZSize / zsize;
mesh.position.x = meshPos.x;
mesh.position.y = meshPos.y - 2; // the parking lot is sligthly under the street level
mesh.position.z = meshPos.z;
mesh.rotation.y = Math.PI/2;
mesh.castShadow = true;
var streetViewOverlay = StreetViewOverlay();
streetViewOverlay.load({streetView: true, objects3D: true, webGL:true}, mesh,48.8049084,2.120357);
}
</script>
</body>
</html>
So here's the thing.. you can covert to three.json format, and that's fine, but the version of your conversion tools have to match the version of three you're using.. you also want to be on close to the most recent three.js version..
but a large issue is that the three.json format is still somewhat in flux between versions, so I have had situations in the past where previously exported models go stale.
If I we're you .. I would use the OBJLoader and load your OBJ directly, or use a format like GLTF or Collada, and their respective loaders. Those formats are less likely to age. Especially GTLF looks like its heading toward being widely supported and has a lot of nice features that make it very efficient for realtime 3d.
r.e. your specific problem: First I would ask if you see any errors in the console from when you load your model. Second, I would put a debug breakpoint on the line inside the loader, and visually inspect the scene and its .children,
OR log it in the code with a scene.traverse((elem)=>{console.log(elem.type,elem);});
If that doesn't show at least one "Mesh" it means your conversion may have had problems.. if it does show, it could mean the mesh is too tiny to see, too Huge to see, or maybe the material is accidently transparent or many other possibilities. At that point, you can look at the mesh.geometry and make sure it has vertices and elements within it...
Failing all that:
If you try with OBJLoader or some other loader, and still can't get it to work.. check back with us. :)

KineticJS, Paint like program, brush gaps

I am trying to do something like paint with KineticJS. I am trying to draw the color with circles that originate from the mouse position. However the eventlistener of the mouse position seems too slow and when I move the mouse too fast the circles drawn are far from each other resulting this:
I have seen people filling array with points drawing lines between them, but I thought thats very bad for optimization because after dubbing the screen too much the canvas starts lagging because it has too much lines that it redraws every frame. I decided to cancel the cleaning of the layer and I am adding new circle at the current mouse position and I remove the old one for optimization. However since Im not drawing lines on fast mouse movement it leaves huge gaps. I would be very grateful if anyone can help me with this.
Here is my code:
(function() {
var stage = new Kinetic.Stage({
container: 'main-drawing-window',
width: 920,
height: 750
}),
workplace = document.getElementById('main-drawing-window'),
layer = new Kinetic.Layer({
clearBeforeDraw: false
}),
border = new Kinetic.Rect({
stroke: "black",
strokeWidth: 2,
x: 0,
y: 0,
width: stage.getWidth(),
height: stage.getHeight()
}),
brush = new Kinetic.Circle({
radius: 20,
fill: 'red',
strokeWidth: 2,
x: 100,
y: 300
});
Input = function() {
this.mouseIsDown = false;
this.mouseX = 0;
this.mouseY = 0;
this.offsetX = 0;
this.offsetY = 0;
};
var input = new Input();
document.documentElement.onmousedown = function(ev) {
input.mouseIsDown = true;
};
document.documentElement.onmouseup = function(ev) {
input.mouseIsDown = false;
};
document.documentElement.onmousemove = function(ev) {
ev = ev || window.event;
// input.mouseX = (ev.clientX - workplace.offsetLeft);
// input.mouseY = (ev.clientY - workplace.offsetTop);
input.mouseX = (ev.offsetX);
input.mouseY = (ev.offsetY);
};
function DistanceBetweenPoints(x1, y1, x2, y2) {
return Math.sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1)));
}
var canvasDraw = setInterval(function() {
// console.log(input);
if (input.mouseIsDown) {
workplace.style.cursor = "crosshair";
var currentBrushPosition = brush.clone();
currentBrushPosition.setX(input.mouseX);
currentBrushPosition.setY(input.mouseY);
// var distance = DistanceBetweenPoints(brush.getX(), brush.getY(), currentBrushPosition.getX(), currentBrushPosition.getY());
// if (distance > brush.getRadius() * 2) {
// var fillingLine = new Kinetic.Line({
// points: [brush.getX(), brush.getY(), currentBrushPosition.getX(), currentBrushPosition.getY()],
// stroke: 'yellow',
// strokeWidth: brush.getRadius()*2,
// lineJoin: 'round'
// });
// // layer.add(fillingLine);
// }
layer.add(currentBrushPosition);
brush.remove();
brush = currentBrushPosition;
layer.draw();
// if (fillingLine) {
// fillingLine.remove();
// }
}
if (!input.mouseIsDown) {
workplace.style.cursor = 'default';
}
}, 16);
layer.add(border);
stage.add(layer);
})();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Coloring Game</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/kineticjs/5.2.0/kinetic.min.js"></script>
</head>
<body>
<div id="main-drawing-window"></div>
<script type="text/javascript" src="./JS files/canvas-draw.js"></script>
</body>
</html>
Don't use individual Kinetic.Circles for each mousemove. Every Kinetic object is a "managed" object and that management takes up a lot of resources. KineticJS will slow to a crawl as the number of circles increases with every mousemove.
Instead, use a Kinetic.Shape and draw you circles onto the canvas with
// This is Pseudo-code since I haven't worked with KineticJS in a while
shapeContext.beginPath();
shapeContext.arc(mouseX,mouseY,20,0,Math.PI*2);
shapeContext.fillStrokeShape(this);
This will probably clear your problem, but if the mouse is moved very far in a single mousemove then you might have to draw a lineTo (instead of arc) between the last mouse point and the current far-away mouse point.

Createjs - Tweenjs doesn't work with Bitmap

I have an example, i want to create animation with easel.js Bitmap but it seems not working. In this project, i use preload.js to load image; crop card in cards picture; create Bitmap object and try to animate this bitmap by using tween.js Anyone can help me. Thank you!
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="Scripts/CanvasLib/easeljs-0.6.1.min.js"></script>
<script src="Scripts/CanvasLib/preloadjs-0.3.1.min.js"></script>
<script src="Scripts/CanvasLib/soundjs-0.4.1.min.js"></script>
<script src="Scripts/CanvasLib/tweenjs-0.4.1.min.js"></script>
</head>
<body>
<canvas id="CanvasDemo" width ="1024" height="768" style="border:1px solid #000000;"> </canvas>
<script>
var queue = new createjs.LoadQueue(),
stage = new createjs.Stage("CanvasDemo"),
text = new createjs.Text("Welcome to canvas demo!", "40px Bold Aria"),
image = {},
card = {};
stage.addChild(text);
//stage.autoClear = false;
queue.addEventListener("complete", handleComplete);
queue.loadManifest([
{ id: "myImage", src: "Images/card.png" }
]);
function handleComplete() {
image = queue.getResult("myImage");
card = new createjs.Bitmap(image);
card.sourceRect = new createjs.Rectangle(56, 74, 56, 74);
stage.addChild(card);
createjs.Tween.get(card).to({ x: 600, y: 1000 }, createjs.Ease.linear);
createjs.Ticker.addListener(this);
}
function tick() {
text.x += 5;
if (text.x >= 1024) {
text.x = 0;
}
text.y = 50 + Math.cos(text.x * 0.1) * 10;
text.color = createjs.Graphics.getHSL(360 * Math.random(), 50, 50);
stage.update();
}
</script>
</body>
</html>
This works just fine - except you skipped the "duration" parameter on the Tween.to call (and instead specified the ease, which is the 3rd parameter). This makes it a 0-duration tween, which ends up off-stage (so you never see it).
Try this instead:
createjs.Tween.get(card).to({ x: 600, y: 1000 }, 1000, createjs.Ease.linear);

Categories