I am trying to develop a simple cross-platform game, and trying to move a PhysicsSprite with a Body to the position I touched/clicked, using Cocos2D-JS.
Here is the code that I have:
var TAG_SPRITE = 1;
var AnimationLayer = cc.Layer.extend({
space:null,
ctor:function (space) {
this._super();
this.space = space;
this.init();
},
init:function () {
this._super();
var winsize = cc.director.getWinSize();
//init physics sprite
var spriteHead = new cc.PhysicsSprite(res.Head_png);
var headContentSize = spriteHead.getContentSize();
//init body
var headBody = new cp.Body(1, cp.momentForBox(1, headContentSize.width, headContentSize.height));
headBody.p = cc.p(winsize.width / 2, winsize.height / 3);
this.space.addBody(headBody);
//init shape
var headShape = new cp.CircleShape(headBody, headContentSize.width / 2, cp.v(0, 0));
headShape.setFriction(0.3);
headShape.setElasticity(0.8);
this.space.addShape(headShape);
spriteHead.setBody(headBody);
this.addChild(spriteHead, 0, TAG_SPRITE);
//for mobile
if('touches' in cc.sys.capabilities ){
cc.eventManager.addListener({
event: cc.EventListener.TOUCH_ONE_BY_ONE,
swallowTouches: true,
onTouchBegan:function (touch, event) {
cc.log('touch began');
event.getCurrentTarget().moveSprite(touch.getLocation());
return true;
},
onTouchMoved: function (touch, event) {
},
onTouchEnded: function (touch, event) {
},
onTouchCancelled: function (touch, event) {
}
}, this);
}
//for desktop
else if ('mouse' in cc.sys.capabilities ) {
cc.eventManager.addListener({
event: cc.EventListener.MOUSE,
onMouseUp: function (event) {
event.getCurrentTarget().moveSprite(event.getLocation());
}
}, this);
}
},
moveSprite:function(position) {
cc.log('move to: ' + position.x + ',' + position.y);
var sprite = this.getChildByTag(TAG_SPRITE);
var moveAction = new cc.moveTo(1, position);
sprite.runAction(moveAction);
}
});
As I see the logs from the logcat, it can handle touch events but cannot move the sprite. When I convert the PhysicsSprite to just Sprite object and remove all other Body and Shape stuff, it can be moved to the location that I touch.
The problem is that I can move the PhysicsSprite in the browser whereas I cannot do that in my Android phone.
Note: I use Chipmunk physics engine
I don't know this is the real solution or should be considered as a workaround but the code below works fine for both web and Android. But still don't know why the code in the question doesn't work for Android while it does for the web. (It would make more sense if it didn't work for both...)
I tried to move body of the sprite instead of itself. The new moveSprite method is like that:
moveSprite: function(sprite){
cc.log('move to: ' + position.x + ',' + position.y);
var sprite = this.getChildByTag(TAG_SPRITE);
var body = sprite.getBody();
var velocity = 300;
this.moveWithVelocity(body, position, velocitiy);
}
moveWithVelocity is the custom function that I created in the same Layer, moving the Body to the destination point with a particular velocity:
moveWithVelocity: function(body, destination, velocity){
var deltaX = destination.x - body.p.x;
var deltaY = destination.y - body.p.y;
var distance = Math.sqrt(Math.pow(deltaX,2) + Math.pow(deltaY,2));
var time = distance / velocity;
var velocityX = deltaX / time;
var velocityY = deltaY / time;
//start the action with the calculated velocity in the calculated direction
body.applyImpulse(cc.v(velocityX, velocityY), cc.v(0,0));
//stop the sprite (or body here) when duration of movement is time out (or when the sprite/body arrives its destination)
setTimeout(function(){
body.setVel(cc.v(0,0));
}, time*1000);
}
Hope this helps anyone encountered the same problem.
Related
I'm trying to create a top down shooter game and I am using Tiled to create my map. I've made my map and exported it as a .json file. I was finally able to make the map appear in my game, but I am having a hard time making the collision work.
I've been going through tutorials for hours and seem to have tried everything under the sun with no luck. I have an object layer in Tiled with the walls marked with the insert rectangle tool. I have every wall tile also marked with insert rectangle in the edit tileset menu. But I still cant get it to work. Walls are Tile Layer 1, ground is Tile Layer 2, object layer is called collision and the tile set name is tiles 48x48. Here's all my relevant code:
var game = new Phaser.Game(1440, 960, Phaser.man, 'phaser-example', { preload: preload, create: create, update: update, render: render });
var sprite
//sounds
var music
//movement
var controls
var cursors
//shooting
var fireRate = 200;
var nextFire = 0;
var Bullets
//map
var map
var walls
var ground
//var collision
function preload() {
game.load.audio('groove', ['sewer groove.mp3']);
game.load.audio('gunshot', 'pistol.mp3');
game.load.image('player', 'player lite.png');
game.load.image('bullet', 'bullet.png');
game.load.tilemap('map', 'sewermap.json', null, Phaser.Tilemap.TILED_JSON);
game.load.image('tiles 48x48','tiles 48x48.png')
}
function create() {
map = game.add.tilemap('map');
map.addTilesetImage('tiles 48x48');
//var tileset = map.addTilesetImage('map','tiles 48x48');
//map.physics.arcade.enable(sprite, Phaser.Physics.ARCADE);
ground = map.createLayer('Tile Layer 2');
walls = map.createLayer('Tile Layer 1');
//collision = map.createLayer('Object Layer 1')
map.setCollisionBetween(0, 65, true, 'Tile Layer 1');
//sprite.body.collideWorldbounds = true;
//layer.resizeWorld();
music = game.add.audio('groove',1,true);
music.play();
game.physics.startSystem(Phaser.Physics.ARCADE);
//game.physics.startSystem(Phaser.Physics.P2JS)
game.stage.backgroundColor = '#313131';
bullets = game.add.group();
bullets.enableBody = true;
bullets.physicsBodyType = Phaser.Physics.ARCADE;
bullets.createMultiple(50, 'bullet');
bullets.setAll('checkWorldBounds', true);
bullets.setAll('outOfBoundsKill', true);
sprite = game.add.sprite(620, 920, 'player');
sprite.anchor.set(0.5, 0.5);
//game.physics.p2.enable(sprite)
game.physics.arcade.enable(sprite, Phaser.Physics.ARCADE);
sprite.body.allowRotation = true;
cursors = game.input.keyboard.createCursorKeys();
}
function update() {
game.physics.arcade.collider(sprite, walls);
//console.log(sprite.rotation);
sprite.rotation = game.physics.arcade.angleToPointer(sprite);
if (game.input.activePointer.isDown)
{
fire();
}
//sprite.body.setZeroVelocity();
if (game.input.keyboard.isDown(Phaser.Keyboard.LEFT))
{
sprite.x -= 4;
}
else if (game.input.keyboard.isDown(Phaser.Keyboard.RIGHT))
{
sprite.x += 4;
}
if (game.input.keyboard.isDown(Phaser.Keyboard.UP))
{
sprite.y -= 4;
}
else if (game.input.keyboard.isDown(Phaser.Keyboard.DOWN))
{
sprite.y += 4;
}
}
function fire() {
if (game.time.now > nextFire && bullets.countDead() > 0)
{
nextFire = game.time.now + fireRate;
var bullet = bullets.getFirstDead();
bullet.reset(sprite.x - 8, sprite.y - 8);
game.physics.arcade.moveToPointer(bullet, 300);
}
}
function render() {
game.debug.text('Active Bullets: ' + bullets.countLiving() + ' / ' + bullets.total, 32, 32);
game.debug.spriteInfo(sprite, 32, 450);
//game.debug.spriteBounds(sprite);
//game.debug.spriteBounds(bullets);
//game.debug.body(sprite);
}
Alright, I've had the chance to take a look at this, the issue should solely lie in how you're moving the main player:
sprite.x -= 4;
Collisions only fire if the body has a velocity, the following table by samme should sum it up
You can apply acceleration, for the sake of example, to move the character towards the direction you're pointing at:
if (game.input.keyboard.isDown(Phaser.Keyboard.UP) || game.input.keyboard.isDown(Phaser.Keyboard.W)) {
game.physics.arcade.accelerationFromRotation(sprite.rotation, 200, sprite.body.acceleration);
}
In the image I'm also applying a certain drag and reducing acceleration when nothing is pressed but that's your call:
sprite.body.drag.x = 200;
sprite.body.drag.y = 200;
If you wanted to strafe an idea could be at dealing with multiple presses and applying a different accelerationFromRotation accordingly (with a variety of degrees converted with Phaser.Math.degToRad)
For debug's sake, if needed, you might want to use some of the following:
[...]
walls = map.createLayer("Tile Layer 1");
walls.debug = true;
[...]
function collisionHandler(obj1, obj2) {
console.log("Colliding!", obj1, obj2)
}
game.physics.arcade.collide(sprite, walls, collisionHandler, null, this);
game.debug.body(sprite);
I want to make a wheel spinning like this, but it not smooth when rotating. How can I make it run smoothly?
Demo
var audioengine = cc.audioEngine;
audioengine.playMusic(res.Wheel_mp3, false);
var spinNumber = Math.floor((Math.random()*360) + 0);
var angle = spinNumber + 13*360;
var action = new cc.RotateBy(18, angle);
var ease = new cc.EaseSineOut(action);
this.sprite.runAction(ease);
I always create a new class extends Sprite and rewrite draw() or update() to do the job.
Here is the example:
var Wheel = Sprite.extend({
ctor and other function : ...
draw : function(){
this._super();
var speed = this. calculate Speed();
var rotation = this.getRotation();
var neoRotation = (rotation+speed)%360;
this.setRotation(neoRotation)
},
caculateSpeed : function(){
// some function that calculate the speed to simulate acceleration and deceleration.
// return 0 means not rotate.
return speed.
}
})
In order to calculate the speed, you may save some parameter(like current speed, current acceleration speed) to record the status.
I'm developing a tool to add various sprites to the stage. When I drag an element I'd like to display o bounding box ( a rectangle ) that need to move accordingly to the dragging item.
To handle the drag functionality I'm using a lib called draggable
This is the constructor of every single object I push on the stage:
function createElement(x, y, ass_id)
{
// create our little bunny friend..
bunny = new PIXI.Sprite(textures[ass_id]);
bunny.scale.x = bunny.scale.y = 0.2;
bunny.draggable({
snap: true,
snapTolerance:0,
grid: [ 50, 50 ],
alpha: 0.5,
mousedown: function(data) {
/*var fishBounds = new PIXI.Rectangle(
-fishBoundsPadding,
-fishBoundsPadding,
viewWidth + fishBoundsPadding * 2,
viewHeight + fishBoundsPadding * 2);*/
texture_w = (data.target.texture.width) * data.target.scale.x;
texture_h = (data.target.texture.height) * data.target.scale.y;
// scale = data.target.scale.x;
var box = new PIXI.Graphics();
box.lineStyle(2, 0x666666);
box.drawRect(data.target.position.x, data.target.position.y, texture_w, texture_h);
box.scale.x = box.scale.y = scale;
stage.addChild(box);
data.target.boundingBox = box;
console.log(data.target.boundingBox.position, data.target.position);
},
drag: function(data) {
offset_x = data.boundingBox.position.x;//data.position;
offset_y = data.boundingBox.position.y;
data.boundingBox.position.x = data.position.x;// * data.scale.x;// - offset_x;
data.boundingBox.position.y = data.position.y;// * data.scale.y;// - offset_y;
console.log(stage.children.length , data.boundingBox.position, data.position, data);
},
mouseup: function(data) {
console.log("drop");
stage.removeChild(data.target.boundingBox);
}
});
// move the sprite to its designated position
bunny.position.x = x;
bunny.position.y = y;
elements.push(bunny);
// add it to the stage
stage.addChild(elements[elements.length-1]);
}
now, this works like a charm: when I click the element a bounding box gets created in the correct location, the problem is that when I start drag it around the bounding box get away from the item. I thing that the reason for this might be due to the fact the one item is scaled, wether the other isn't, but since I'm a noob at pixi I really find myself stuck with it.
Ok, I discovered that you can easily and conveniently attach an object to another via the addChild, so it comes out like this:
function createElement(x, y, ass_id)
{
// create our little bunny friend..
bunny = new PIXI.Sprite(textures[ass_id]);
bunny.scale.x = bunny.scale.y = 0.2;
bunny.draggable({
snap: true,
snapTolerance:0,
grid: [ 50, 50 ],
alpha: 0.5,
mousedown: function(data) {
texture_w = (data.target.texture.width);
texture_h = (data.target.texture.height);
var box = new PIXI.Graphics();
box.lineStyle(5, 0x666666);
box.drawRect(0, 0, texture_w, texture_h);
data.target.type = "element";
data.target.addChild(box);
},
drag: function(data) {
},
mouseup: function(data) {
console.log("drop");
for (var i = stage.children.length - 1; i >= 0; i--) {
if((stage.children[i].type) && (stage.children[i].type == "element"))
for (var j = stage.children[i].length - 1; i >= 0; i--) {
console.log('remove boundingBox child here when needed');
}
};
}
});
// move the sprite to its designated position
bunny.position.x = x;
bunny.position.y = y;
elements.push(bunny);
// add it to the stage
stage.addChild(elements[elements.length-1]);
}
I am trying to make an image object rotate in accordance to the mouse being clicked down on that image and the angle of the mouse to the center of the object.
Think of a unit circle and having the image being rotated about the circle based on where the mouse is on that circle.
I currently have
var stage = new Kinetic.Stage({
container: "container",
width: 800,
height: 500,
id: "myCanvas",
name: "myCanvas"
});
var layer = new Kinetic.Layer();
//gets the canvas context
var canvas = stage.getContainer();
var mousePosX;
var mousePosY;
var mouseStartAngle;
var selectedImage;
var mouseAngle;
var mouseStartAngle;
console.log(canvas)
var shiftPressed
window.addEventListener('keydown', function (e) {
if (e.keyCode == "16") {
shiftPressed = true;
}
console.log(shiftPressed)
}, true);
window.addEventListener('keyup', function (e) {
if (e.keyCode == "16") {
shiftPressed = false;
}
console.log(shiftPressed)
}, true);
function drawImage(imageObj) {
var dynamicImg = new Kinetic.Image({
image: imageObj,
x: stage.getWidth() / 2 - 200 / 2,
y: stage.getHeight() / 2 - 137 / 2,
width: 100, //imageObj.width,
height: 100, // imageObj.height,
draggable: true,
offset: [50,50] //[(imageObj.width/2), (imageObj.height/2)]
});
dynamicImg.on('mousedown', function () {
selectedImage = this;
console.log("x: " + this.getX())
console.log("y: " + this.getY())
var mouseStartXFromCenter = mousePosX - (this.getX() + (this.getWidth() / 2));
var mouseStartYFromCenter = mousePosY - (this.getY() + (this.getHeight() / 2));
mouseStartAngle = Math.atan2(mouseStartYFromCenter, mouseStartXFromCenter);
if (shiftPressed) {
//console.log("trying to switch draggable to false");
//console.log(this)
this.setDraggable(false);
}
});
dynamicImg.on('mouseup mouseout', function () {
//console.log('mouseup mouseout')
this.setDraggable(true);
});
dynamicImg.on('mouseover', function () {
document.body.style.cursor = 'pointer';
});
dynamicImg.on('mouseout', function () {
document.body.style.cursor = 'default';
});
imageArray.push(dynamicImg);
layer.add(dynamicImg);
stage.add(layer);
}
var imageObj = new Image();
imageObj.onload = function () {
drawImage(this);
};
imageObj.src = 'http://localhost:60145/Images/orderedList8.png';
function getMousePos(evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
canvas.addEventListener('mouseup', function () {
selectedImage = undefined;
});
canvas.addEventListener('mousemove', function (evt) {
mousePos = getMousePos(evt);
//console.log('Mouse position: ' + mousePos.x + ',' + mousePos.y)
mousePosX = mousePos.x;
mousePosY = mousePos.y;
if (selectedImage != undefined) {
mouseXFromCenter = mousePosX - selectedImage.getX();
mouseYFromCenter = mousePosY - selectedImage.getY();
mouseAngle = Math.atan2(mouseYFromCenter, mouseXFromCenter);
var rotateAngle = mouseAngle - mouseStartAngle;
selectedImage.setRotation(rotateAngle);
}
}, false);
the code has a couple things to it.
-It should only allow a rotate if 'shift' is pressed and mousedown event happens on an image.
-it needs to maintain the dynamic image drawing as they will be populating the canvas dynamically over the life of the page.
here is a good example of something similar i want to happen, but just simply cannot get it to work in canvas/kineticjs.
http://jsfiddle.net/22Feh/5/
I would go simpler way using dragBoundFunc. http://jsfiddle.net/bighostkim/vqGmL/
dragBoundFunc: function (pos, evt) {
if (evt.shiftKey) {
var x = this.getX() - pos.x;
var y = this.getY() - pos.y;
var radian = Math.PI + Math.atan(y/x);
this.setRotation(radian);
return {
x: this.getX(),
y: this.getY()
}
} else {
return pos;
}
}
My mistake, I misread your question. You were essentially missing one line:
layer.draw();
Hold shift and move the mouse, you'll see it rotates nicely.
http://jsfiddle.net/WXHe6/2/
canvas.addEventListener('mousemove', function (evt) {
mousePos = getMousePos(evt);
//console.log('Mouse position: ' + mousePos.x + ',' + mousePos.y)
mousePosX = mousePos.x;
mousePosY = mousePos.y;
if (selectedImage != undefined) {
mouseXFromCenter = mousePosX - selectedImage.getX();
mouseYFromCenter = mousePosY - selectedImage.getY();
mouseAngle = Math.atan2(mouseYFromCenter, mouseXFromCenter);
var rotateAngle = mouseAngle - mouseStartAngle;
selectedImage.setRotation(rotateAngle);
layer.draw(); // <--------------- right here
}
}, false);
You should be more clear what your .on() events do. In your code, the mousedown on the shape doesn't do anything other than calculate an mouseStartAngle, but doesn't do anything. And your mouseUp on the shape event doesn't do much either. It's your browser/client mousedown/mouseup that do all the work, and that's why it rotates properly on some clicks and not others.
For setting the rotation you have many options, here are two:
Option one: set the radians manually on mousedown
dynamicImg.on('mousedown', function () {
dynamicImg.setRotation(mouseStartAngle); //set the rotation degree
layer.draw(); // redraw the layer
}
Option two: let kineticJS animate the rotation for you
dynamicImg.on('mousedown', function () {
dynamicImg.transitionTo({
duration: 1, // length of animation in seconds
rotation: mouseStartAngle // your angle, in radians
});
}
your updated jsfiddle: http://jsfiddle.net/WXHe6/1/
Here are some additional notes:
The reason you are having trouble is because your code is structured is a bit of a messy manner, sorry to say. You are mixing browser events with and adding listeners to the canvas rather than using built-in kineticJS functionality, for example, you could use stage.getUserPosition() to get the mouse coordinates. Unless you have some dire need to structure your project this way, try to avoid it.
What I do like is that you have created functions to break up your code, but on the down-side you have multiple functions doing the same thing, like calculating and updating the rotation angle. Why not just make one function to get the angle?
Some Tips:
Try using mainly KineticJS for functionality (I know you'll need event listeners for buttons like SHIFT). What I mean is, use things like stage.getUserPosition(); to get the mouse/touch coordinates, rather than evt.clientX, it's cleaner, and the work has been done for you already, no need to re-invent the wheel.
Make one function for setting/getting the rotation for a shape. Then you can call it whenever you want. (use less repetitive code)
If you don't want the shape to be draggable when shift is clicked, you should set that before an item is clicked. You have button listeners so you can either disable rotation for all shapes when shift is pressed down, or just for a shape on that is under the cursor.
imageArray.push(dynamicImg); not sure if you really need this, if you need to access all the elements as an array, you could alway do layer.getChildren(); to get all the images in the layer, or access them numerically like layer.getChildren()[0]; (in creation order)
I'm trying to draw elements to a canvas and then allow the user to resize them by clicking and dragging them. I've implemented this with Kinetic JS library, but my development team is moving over to Easel JS.
Here is the code with the Kinetic library.
This works well enough.
I get about this far in Easel JS, but this code doesn't do anything. The canvas is totally blank. I realize that I'm not sure how to:
call mouse events -- here I'm trying to attach them to the DOM element, as in this tutorial
where to set the resize function -- separate function? called within the tick() function?
grab the mouse coordinates
var canvas;
var stage;
var rect;
var mousePos = new Point();
var update = true;
var rectX = 10;
var rectY = 10;
var rectW = 100;
var rectH = 50;
var rectXOffset = 50;
var rectYOffset = 50;
var newWidth;
var newHeight;
function init() {
// create stage and point it to the canvas:
canvas = document.getElementById("testCanvas");
stage = new Stage(canvas);
// overlay canvas used to draw target and line
canvasWrapper = $("#testCanvas");
// listen for a mouse down event
canvasWrapper.mousedown(onMouseDown);
// listen for mouse up event
canvasWrapper.mouseup(onMouseUp);
// enable touch interactions if supported on the current device:
if (Touch.isSupported()) { Touch.enable(stage); }
// enabled mouse over / out events
stage.enableMouseOver(10);
// start drawing instructions
var rect = new Shape();
rect.graphics
.setStrokeStyle(1)
.beginStroke(Graphics.getRGB(25,25,112,.7))
.drawRect(rectX,rectY,rectW,rectH);
// add rectangle to stage
stage.addChild(rect);
// render stage
stage.update();
// set the tick interval to 24 fps
Tick.setInterval(1000/24);
// listen for tick event
Tick.addListener(window, true);
// pause
Tick.setPaused(false);
}
//called when user clicks on canvas
function onMouseDown(e) {
mousePos.x = e.stageX;
mousePos.y = e.stageY
// check to see if mouse is within offset of rectangle
if(mousePos.x <= (rectW + rectXOffset) || mousePos.y <= (rectH + rectYOffset)) {
// set update to true
update = true;
// unpause tick
Tick.setPaused(false);
}
}
function onMouseUp(e) {
update = false;
Tick.setPaused(true);
}
function tick() {
// this set makes it so the stage only re-renders when an event handler indicates a change has happened.
if (update) {
if(mousePos.x - rectX < 50)
{
newWidth = 50;
} else {
newWidth = mousePos.x - rectX;
}
if(mousePos.y - rectY < 50)
{
newHeight = 50;
} else {
newHeight = mousePos.y -rectY;
}
rectW = newWidth;
rectH = newHeight;
rect.clear();
rect.graphics
.setStrokeStyle(1)
.beginStroke(Graphics.getRGB(65,65,65,.7))
.drawRect(0,0,rectW,rectH);
// add rectangle to stage
stage.addChild(rect);
update = false; // only update once
stage.update();
}
}
I know it shouldn't be this difficult and would appreciate any help.