Detect collision direction in Phaser3 - phaser-framework

I'm trying to create a 'Bomber-man' like game using Phaser3 library.
For this purpose I'd like to define a collision relationship between the player and the bricks,
and more importantly - detect the collision direction relative the the player.
I've noticed body properties like touching or blocked but they are always set to false. (please see below)
//scene.js
// bricks static group
this.scene.physics.add.staticGroup({ immovable: true });
// player defined in external file (as sprite)
this.player = new Player(this, 90, 90)
// player.js
// ...
this.physics.add.collider(
this,
scene.bricks,
function(player, brick) {
if(player.body.touching.left) { //ALWAYS FALSE!!!
this.isBlockedFromLeft = true;
}, else if(player.body.touching.right) {
this.isBlockedFromRight = true; // ALWAYS FALSE!!!
}
},
null,
this
);
I'd appreciate any help. This is driving me crazy. Maybe there is a better way to do it and i'm missing something...
Thanks in advance.

So I finally figured it out.
The major issue was the way I defined the player movement. It should be
if (this.keyboard.right.isDown) {
this.body.setVelocityX(this.speed);
}
rather than
if (this.keyboard.right.isDown) {
this.x += this.speed;
}
The second way prevent collision detection and the body.touching and body.blocked properties to be updated.
Furthermore, I've found out that when it comes to top-down tiled games, it's really easier to build up the game using the tile-map feature.
official examples can be found here:
https://phaser.io/examples/v3/search?search=map
and here is a tutorial of how to make a tiled-map using a light-weight software called 'Tiled'
https://www.youtube.com/watch?v=2_x1dOvgF1E
Thank you all!

Related

HoloLens spatial mapping.SpatialSurfaceMesh update problem. C++/winrt

im working on the spatial mapping processing for my HoloLens project.
Somehow calling "SpatialSurfaceMesh::TryComputeLatestMeshAsync" keeps returning the same mesh data overtime.
Is there another process involved updating the observer?
void SpatialMapping::AddOrUpdateSurface(winrt::Windows::Perception::Spatial::SpatialCoordinateSystem const& coordinateSystem)
{
using namespace winrt::Windows::Perception::Spatial::Surfaces;
SpatialBoundingBox axisAlignedBoundingBox =
{
{ 0.f, 0.f, 0.f },
{ 50.f, 50.f, 50.f },
};
SpatialBoundingVolume bounds = SpatialBoundingVolume::FromBox(coordinateSystem, axisAlignedBoundingBox);
m_surfaceObserver.SetBoundingVolume(bounds);
m_surfaceObserver.ObservedSurfacesChanged(
winrt::Windows::Foundation::TypedEventHandler
<SpatialSurfaceObserver, winrt::Windows::Foundation::IInspectable>
({ this, &SpatialMapping::Observer_ObservedSurfacesChanged })
);
}
void SpatialMapping::Observer_ObservedSurfacesChanged(winrt::Windows::Perception::Spatial::Surfaces::SpatialSurfaceObserver const& sender
, winrt::Windows::Foundation::IInspectable const& object)
{
{
using namespace winrt::Windows::Perception::Spatial::Surfaces;
const auto mapContainingSurfaceCollection = sender.GetObservedSurfaces();
// Process surface adds and updates?.
for (const auto& pair : mapContainingSurfaceCollection)
{
auto id = pair.Key();
auto info = pair.Value();
InsertAsync(id, info);
}
}
}
Concurrency::task<void> SpatialMapping::InsertAsync(winrt::guid /*const&*/ id, winrt::Windows::Perception::Spatial::Surfaces::SpatialSurfaceInfo /*const&*/ newSurfaceInfo)
{
using namespace winrt::Windows::Perception::Spatial::Surfaces;
return concurrency::create_task([this, id, newSurfaceInfo]
{
const auto surfaceMesh = newSurfaceInfo.TryComputeLatestMeshAsync(m_maxTrianglesPerCubicMeter, m_surfaceMeshOptions).get();
std::lock_guard<std::mutex> guard(m_meshCollectionLock);
m_updatedSurfaces.emplace(id, surfaceMesh);
});
}
Generation works, Update does not
Manuel attempt same problem:
winrt::Windows::Foundation::IAsyncAction SpatialMapping::CollectSurfacesManuel()
{
const auto mapContainingSurfaceCollection = m_surfaceObserver.GetObservedSurfaces();
for (const auto& pair : mapContainingSurfaceCollection)
{
auto id = pair.Key();
auto info = pair.Value();
auto mesh{ co_await info.TryComputeLatestMeshAsync(m_maxTrianglesPerCubicMeter, m_surfaceMeshOptions) };
{
std::lock_guard<std::mutex> guard(m_meshCollectionLock);
m_updatedSurfaces.emplace(id, mesh);
}
}
}
MVCE:
Create a New Project with the template
"Holographic DirectX 11 App (UWP) C++/WinRT)"
Add the files:
https://github.com/lpnxDX/HL_MVCE_SpatialSurfaceMeshUpdateProblem.git
Replace m_main in AppView.h
We did some research and have some thoughts about your question right now, let me explain the findings
Has your Observer_ObservedSurfacesChanged method triggered exactly? Adding output statements or breakpoints can help you check it. Since SurfaceObserver should be always available, usually we need to check the availability of surfaceObserver in each frame and recreate a new one when necessary, sample code snippt please see here.
Have you set m_surfaceMeshOptions? It is not visible in the code you posted. If it is missing, you can configure it with the following statement:
surfaceMeshOptions-> IncludeVertexNormals = true;
Microsoft provided the Holographic spatial mapping sample, shows how to acquire spatial mapping data from Windows Perception in real-time. it is similar to your needs, to narrow down issue if it's an issue with your code, please try to check and run this example on your device
If after the above steps, you still can't solve the problem, could you provide an
MVCE, so that we can locate the issue or find a solution? Be careful to remove any privacy-related or other business function codes.
Your code has the following problems:
TryComputeLatestMeshAsync should be called from Observer_ObservedSurfacesChanged not from concurrency::create_task
TryComputeLatestMeshAsync return mesh with matrix, vertices and indices. Indices should be stored to a safe location at the first run, they don't change later. Vertices and matrix should copied as they returns. You shouldn't save the mesh itself, because its data updates from various threads.
ObservedSurfacesChanged shouldn't be called every frame. This is long running function.
Maybe it has something more. I would recommend to start from the sample mentioned earlier.

Phaser.events.onInputOut not dispatched

I'm trying to make a sprite moving when the mouse is over it and I'd like it to stop when the mouse is not over it anymore.
Here is my code:
mySprite.events.onInputOver.add(() => touchMouse = true);
mySprite.events.onInputOut.add(() => touchMouse = false);
and
update() {
if (touchMouse) {
mySprite.x += 5;
}
}
My sprite is correctly moving but the onInputOut signal is not dispatched if I don't move the pointer out of theĀ initialĀ sprite position!! This result in my sprite moving out of my pointer and continuing its journey until I move my mouse...
Is it a phaser bug? Has anyone a solution to make this work?
Thank you very much and have a good day,
Simon
Edit:
I just tried to use the Phaser.InputHandler object instead but I got the same kind of bug. Here is the code:
update() {
if (mySprite.input.pointerOver()) {
mySprite.x += 5;
}
}
Someone answered my question in the html5gamedevs forum.
Phaser doesn't ordinarily update inputOver/inputOut events while the pointer isn't moving. You need to set pointer.dirty = true for that.

Moving objects collision Phaser [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
My collision of moving objects is not working. I have created a demo so you can see it and see my problem all code and everything included.
As you may be able to see, I have 2 blocks coming from left to right and then I have a tank shooting bullets> I tried in all kind of directions and I always get the same results, basically my collision only works the velocity of the blocks value, in the example on the zip file only works up to 300px. Depending on the blocks speed, if I change the block speed to a greater number then the collision works on the same numbers pixels. it is really weird.
I was wondering if I'm just doing the whole thing wrong or what could my problem be? I would appreciate any pointers or ideas that can help me solve this issue. Thanks.
Demo source code.
BasicGame.Game = function (game) {
// When a State is added to Phaser it automatically has the following properties set on it, even if they already exist:
this.game; // a reference to the currently running game (Phaser.Game)
this.add; // used to add sprites, text, groups, etc (Phaser.GameObjectFactory)
this.camera; // a reference to the game camera (Phaser.Camera)
this.cache; // the game cache (Phaser.Cache)
this.input; // the global input manager. You can access this.input.keyboard, this.input.mouse, as well from it. (Phaser.Input)
this.load; // for preloading assets (Phaser.Loader)
this.math; // lots of useful common math operations (Phaser.Math)
this.sound; // the sound manager - add a sound, play one, set-up markers, etc (Phaser.SoundManager)
this.stage; // the game stage (Phaser.Stage)
this.time; // the clock (Phaser.Time)
this.tweens; // the tween manager (Phaser.TweenManager)
this.state; // the state manager (Phaser.StateManager)
this.world; // the game world (Phaser.World)
this.particles; // the particle manager (Phaser.Particles)
this.physics; // the physics manager (Phaser.Physics)
this.rnd; // the repeatable random number generator (Phaser.RandomDataGenerator)
// You can use any of these from any function within this State.
// But do consider them as being 'reserved words', i.e. don't create a property for your own game called "world" or you'll over-write the world reference.
this.bulletTimer = 0;
};
BasicGame.Game.prototype = {
create: function () {
//Enable physics
// Set the physics system
this.game.physics.startSystem(Phaser.Physics.ARCADE);
//End of physics
// Honestly, just about anything could go here. It's YOUR game after all. Eat your heart out!
this.createBullets();
this.createTanque();
this.timerBloques = this.time.events.loop(1500, this.createOnebloque, this);
},
update: function () {
if(this.game.input.activePointer.isDown){
this.fireBullet();
}
this.game.physics.arcade.overlap(this.bullets, this.bloque, this.collisionBulletBloque, null, this);
},
createBullets: function() {
this.bullets = this.game.add.group();
this.bullets.enableBody = true;
this.bullets.physicsBodyType = Phaser.Physics.ARCADE;
this.bullets.createMultiple(100, 'bulletSprite');
this.bullets.setAll('anchor.x', 0.5);
this.bullets.setAll('anchor.y', 1);
this.bullets.setAll('outOfBoundsKill', true);
this.bullets.setAll('checkWorldBounds', true);
},
fireBullet: function(){
if (this.bulletTimer < this.game.time.time) {
this.bulletTimer = this.game.time.time + 1400;
this.bullet = this.bullets.getFirstExists(false);
if (this.bullet) {
this.bullet.reset(this.tanque.x, this.tanque.y - 20);
this.game.physics.arcade.enable(this.bullet);
this.bullet.enableBody = true;
this.bullet.body.velocity.y = -800;
}
}
},
createOnebloque: function(){
this.bloquecs = ["bloqueSprite","bloquelSprite"];
this.bloquesr = this.bloquecs[Math.floor(Math.random()*2)];
this.bloque = this.add.sprite(0, 360, this.bloquesr);
this.game.physics.arcade.enable(this.bloque);
this.bloque.enableBody = true;
this.bloque.body.velocity.x = 300;
this.bloque.body.kinematic = true;
this.bloque.checkWorldBounds = true;
this.bloque.outOfBoundsKill = true;
this.bloque.body.immovable = true;
},
createTanque: function() {
this.tanqueBounds = new Phaser.Rectangle(0, 600, 1024, 150);
this.tanque = this.add.sprite(500, 700, 'tanqueSprite');
this.tanque.inputEnabled = true;
this.tanque.input.enableDrag(true);
this.tanque.anchor.setTo(0.5,0.5);
this.tanque.input.boundsRect = this.tanqueBounds;
},
collisionBulletBloque: function(bullet, bloque) {
this.bullet.kill();
},
quitGame: function (pointer) {
// Here you should destroy anything you no longer need.
// Stop music, delete sprites, purge caches, free resources, all that good stuff.
// Then let's go back to the main menu.
this.state.start('MainMenu');
}
};
The code definitely helps, but you can actually get an idea of what's happening just from playing the game.
As the blocks are going by you can actually get the bullets to disappear if you fire and hit the right edge of the center-most block.
What's happening is that you're checking for a collision between the bullets and a block, but the block is getting redefined every time you add a new one to the screen on the left.
What you probably want to do is create a pool of blocks (bloquePool for example), almost exactly like what you're doing in createBullets with your bullet pool (what you've called bullets).
Then check for a collision between the group of bullets and the group of blocks.
this.game.physics.arcade.overlap(
this.bullets, this.bloquePool, this.collisionBulletBloque, null, this
);
You should get the individual bullet and the individual block that collided passed into collisionBulletBloque so you can still kill the bullet as you are.

Nivo Slider - Hide thumbnails if there is only one image and prevent slideshow transitions

I am using the Nivo Slider for the first time and it is absolutely awesome however I do have a couple of issues.
I have it integrated within a CMS and this allows the user to add up to 5 images.
If there is only one image however, I would like to just hide the thumbnails and stop any transitions, as in sliding the same image in again and again.
Now is this something I would do with JQuery or should I be editing the 'jquery.nivo.slider.js' file? Or is it potentially something I could potentially accomplis in both?
I guess I am looking to do something like:
if images < 1 {
transition = false;
thumbnails = hide;
}
Hopefully that makes sense.
Thanks for your time and help.
UPDATE
Okay so I have managed to hide the thumbnails if there is only one image by adding the following to the jquery.nivo.slider.js file:
if (vars.totalSlides < 2)
{
$('.nivo-controlNav').remove();
}
I now want to be able to change one of the settings in the following piece of code based on the same rule but am not sure how to do this:
$.fn.nivoSlider.defaults = {
pauseOnHover: 'false',
......
}
I would change the config array and initialize the slider like this:
// nivo config array
var nivoConfig = {
slices: 30, // For slice animations
boxCols: 16, // For box animations
// put all your init config here but exclude 'effects'
}
if(imagesCount < 2) {
nivoConfig['effects'] = 'none';
} else {
nivoConfig['effects'] = 'random';
}
$('#slider').nivoSlider(nivoConfig);
Try it out, it should work in a way like this.
I had this exact same problem; Johnny's code worked perfectly, but I wanted to elaborate for people who may be having problems with this. You'll want to insert:
if (vars.totalSlides < 2) {
$('.nivo-controlNav').remove();
}
on or around line 158 in the jquery.nivo.slider.js file (within the if(settings.controlNav) {} conditional). Otherwise it won't work.

andengine removing collectable objects like Sprites

im developing a game using andangine and the tmx and body2d extensions.
i create Objects(sprites) like coins an specific positions while creating my map.
i use a contactlistener to check if the player collides with a coin.
how can i delete this sprite?
and how can i organize my sprites best?
thanks =)
I assume you create a PhysicsConnector to connect between your sprites and bodies. Create a list of these physics connectors, and when you decide you should remove a body (And its sprite), do the following:
Body bodyToRemove = //Get it from your contact listener
for(PhysicsConnector connector : mPhysicsConnectors) //mPhysicsConnectors is the list of your coins physics connectors.
if(connector.getBody() == bodyToRemove)
removeSpriteAndBody(connector); //This method should also delete the physics connector itself from the connectors list.
About sprites organization: Coins are re-useable sprite, you shouldn't recreate them every time. You can use an object pool, here's a question about this topic.
I advice you to set user data of a body. And in your collision handler you would be able to work with it. Small example:
body.setUserData(...);
..
public void postSolve(Contact contact, ContactImpulse impulse) {
... bodyAType = (...) bodyA.getUserData();
... bodyBType = (...) bodyB.getUserData();
if (bodyAType != null && bodyBType != null) {
if (bodyAType.getUserData.equals(...)) {
//.......do what you need
}
}
}

Resources