HaxeFlixel tilemap collisions - collections

I am developing a game in Haxe with the HaxeFlixel Framework.
I decided to split the map in chunks so i can load new areas of the map at runtime (without loading screen). For that i put every chunk in an instance of FlxTilemap.
Now I noticed that, when i try to move a FlxTilemap (by changing its x and y properties) the collision detection (with FlxG.collide(hero, map)) does not work right.
To test why the collision detection doesn't work, I simply added a FlxTilemap to the scene and collided it with my hero:
map = new FlxTilemap();
var mapData = "";
for (y in 0...8) {
for (x in 0...8) {
mapData += "0,";
}
mapData += "\n";
}
map.loadMap(mapData, AssetPaths.tuxemon_sprites__png, 16, 16);
for (x in 0...8) {
map.setTile(x, 6, SpriteSheet.TILES.FENCE.LOOSE_1_RIGHT);
}
for (y in 0...8) {
map.setTile(6, y, SpriteSheet.TILES.FENCE.LOOSE_1_RIGHT);
}
map.setPosition(
map.x - map.width / 2,
map.y - map.height / 2
);
add(map);
Collision detection is handeled in the update() method of the state:
override public function update():Void
{
super.update();
FlxG.collide(hero, map);
}
Am I doing it the wrong way or did I simply miss something?
EDIT:
There seems to be a problem in the HaxeFlixel collision detection.
The collision will only be detected when the x and y properties of the FlxObjects are positive.
I want to have negative x/y positions as well.
Does anyone know a fix or workaround for this problem?

Try changing the bounds of your world space. Specifically, FlxG.worldBounds.

Related

Matter.js Gravity Point

Is it possible to create a single gravity / force point in matter.js that is at the center of x/y coordinates?
I have managed to do it with d3.js but wanted to enquire about matter.js as it has the ability to use multiple polyshapes.
http://bl.ocks.org/mbostock/1021841
The illustrious answer has arisen:
not sure if there is any interest in this. I'm a fan of what you have created. In my latest project, I used matter-js but I needed elements to gravitate to a specific point, rather than into a general direction. That was very easily accomplished. I was wondering if you are interested in that feature as well, it would not break anything.
All one has to do is setting engine.world.gravity.isPoint = true and then the gravity vector is used as point, rather than a direction. One might set:
engine.world.gravity.x = 355;
engine.world.gravity.y = 125;
engine.world.gravity.isPoint = true;
and all objects will gravitate to that point.
If this is not within the scope of this engine, I understand. Either way, thanks for the great work.
You can do this with the matter-attractors plugin. Here's their basic example:
Matter.use(
'matter-attractors' // PLUGIN_NAME
);
var Engine = Matter.Engine,
Events = Matter.Events,
Runner = Matter.Runner,
Render = Matter.Render,
World = Matter.World,
Body = Matter.Body,
Mouse = Matter.Mouse,
Common = Matter.Common,
Bodies = Matter.Bodies;
// create engine
var engine = Engine.create();
// create renderer
var render = Render.create({
element: document.body,
engine: engine,
options: {
width: Math.min(document.documentElement.clientWidth, 1024),
height: Math.min(document.documentElement.clientHeight, 1024),
wireframes: false
}
});
// create runner
var runner = Runner.create();
Runner.run(runner, engine);
Render.run(render);
// create demo scene
var world = engine.world;
world.gravity.scale = 0;
// create a body with an attractor
var attractiveBody = Bodies.circle(
render.options.width / 2,
render.options.height / 2,
50,
{
isStatic: true,
// example of an attractor function that
// returns a force vector that applies to bodyB
plugin: {
attractors: [
function(bodyA, bodyB) {
return {
x: (bodyA.position.x - bodyB.position.x) * 1e-6,
y: (bodyA.position.y - bodyB.position.y) * 1e-6,
};
}
]
}
});
World.add(world, attractiveBody);
// add some bodies that to be attracted
for (var i = 0; i < 150; i += 1) {
var body = Bodies.polygon(
Common.random(0, render.options.width),
Common.random(0, render.options.height),
Common.random(1, 5),
Common.random() > 0.9 ? Common.random(15, 25) : Common.random(5, 10)
);
World.add(world, body);
}
// add mouse control
var mouse = Mouse.create(render.canvas);
Events.on(engine, 'afterUpdate', function() {
if (!mouse.position.x) {
return;
}
// smoothly move the attractor body towards the mouse
Body.translate(attractiveBody, {
x: (mouse.position.x - attractiveBody.position.x) * 0.25,
y: (mouse.position.y - attractiveBody.position.y) * 0.25
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.12.0/matter.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/matter-attractors#0.1.6/build/matter-attractors.min.js"></script>
Historical note: the "gravity point" functionality was proposed as a feature in MJS as PR #132 but it was closed, with the author of MJS (liabru) offering the matter-attractors plugin as an alternate. At the time of writing, this answer misleadingly seems to indicate that functionality from the PR was in fact merged.
Unfortunately, the attractors library is 6 years outdated at the time of writing and raises a warning when using a newer version of MJS than 0.12.0. From discussion in issue #11, it sounds like it's OK to ignore the warning and use this plugin with, for example, 0.18.0. Here's the warning:
matter-js: Plugin.use: matter-attractors#0.1.4 is for matter-js#^0.12.0 but installed on matter-js#0.18.0.
Behavior seemed fine on cursory glance, but I'll keep 0.12.0 in the above example to silence it anyway. If you do update to a recent version, note that Matter.World is deprecated and should be replaced with Matter.Composite and engine.gravity.

How to suitably avoid RangeErrors when "looking around" this 2D array?

I have a 2D array structure to represent a grid of tiles that is a part of the game I am making. One aspect of the game is that the grid is filled in in a somewhat random fashion, based on analysis of a text file. Right from the outset though, I already realised that just leaving it be pretty much randomly done like this without sticking in some kind of validity checks or prevention mechanism, to stop really badly configured grid from forming, would not work out. The main problem I want to avoid is too many tiles that would be untraversable being close together, potentially severing chunks of the grid from the rest.
The idea I came up with to try avoid some really bad grids is to check when assigning a tile value to each "grid square" during generation with logic like this
if (tileBeingInserted.isTraversable()) {
//all is well
return true;
} else {
//we may have a problem, are there too many untraversables nearby?
//Proceed to check all squares "around" the current one.
}
To be clear, checking around the current square means checking the square immediately adjacent in each of the 8 cardinal directions. Now, my problem is that I am trying to reason out how to code this so that it will certainly not give a RangeErrorat any point or at least catch it and recover if it must. As an example, you could clearly take one of the corner squares to be the worst scenario in the sense that only 2 of the squares the algorithm would want to check are within the array's bounds. Naturally, if a RangeErrorhappens for this reason I just want the program to progress onward without issue so the structure
try {
//check1
//check2...8
} catch (RangeError e) {
}
is unacceptable because as soon as a single out of range square is tested the code falls out of the check block. An alternative I thought of, but do not like because of its messiness, would be to individually wrap each check in a try-catch and yes that would work I guess but that's some horrid looking code...so can anyone help me out here? Is there perhaps a different angle from which to come at this problem of avoiding the RangeErrors that I am not seeing?
So my code for testing whether another untraversable tile should be placed has shaped up like this:
bool _tileFitsWell(int tileTypeInt, int row, int col)
{
//...initialise some things, set stuff up
...
if (tile.traversable == true) {
//In this case a new traversable tile is being put in, so no problems.
return true;
} else {
//begin testing what tiles are around the current tile
//Test NW adjacent
if (row > 0 && col > 0) {
temp = tileAt(row - 1, col - 1);
if (!temp.traversable) {
strikeCount++;
}
}
//Test N adjacent
if (row > 0) {
temp = tileAt(row - 1, col - 1);
if (!temp.traversable) {
strikeCount++;
}
}
//Test NE adjacent
if (row > 0 && col < _grid[0].length - 2) {
temp = tileAt(row - 1, col 1);
if (!temp.traversable) {
strikeCount++;
}
}
//Test W adjacent
if (col > 0) {
temp = tileAt(row, col - 1);
if (!temp.traversable) {
strikeCount++;
}
}
}
return strikeCount < 2;
}
The code inside each "initial" if-statement (the ones that check row and col) is a bit pseudocode-ish for simplicity's sake. As I explained in a previous comment, the reason why I don't need to check tiles in the other 4 cardinal directions is since these checks are done while filling the map, tiles in those positions will always be either uninitialised or just out of bounds, depending on what tile the function is called to check at a given time.

instantiate plane with texture between two objects(vectors)

First a little context.
I am attempting to build a little fence-builder functionality.
Below is a sketch showing idea/how I see it approached.
Ohh not enough rep apparently: link here: [http://imgur.com/ZougnQi][1]
Two objects are instantiated(Pole1 & Pole2)
As I in runtime move those two poles around the terrain, I wish to
a: create a plane with a texture between those poles (a tileable transparent fence thingy)
which in update ofcourse scales according to the distance between those two points/poles.
b: instantiate new poles according to distance between the two poles.
So far I have per pictures linked two poles I can drag around and a third pole being placed exactly between those two.
I found another post: Instantiate gameobject between 2 objects in unity 3d
But couldn't get code from "SlxS" to work, and it does not really aid in me creating a textured plane/cube between the poles.
Code that works:
function Update ()
{
poles.transform.position = 0.5f*(pole1.transform.position + pole2.transform.position);
}
var pole1 : Transform;
var pole2 : Transform;
var poles : GameObject;
var selectedDistance : int = 5;
function Build()
{
var distance = Vector3.Distance(pole1.transform.position,pole2.transform.position);
print(distance);
poles.transform.position = 0.5f*(pole1.transform.position + pole2.transform.position);
if((pole1.transform.position - pole2.transform.position).magnitude < selectedDistance)
{
print("more than 5 apart");
}
else
{
print("less than 5 apart");
}
}
Hope to get some input :)
Best,
[1]: http://imgur.com/ZougnQi
SOLVED: Thanks to https://stackoverflow.com/users/685314/joetjah
Code:
function Update ()
{
poles.transform.position = 0.5f*(pole1.transform.position + pole2.transform.position);
}
var pole1 : Transform;
var pole2 : Transform;
var poles : Transform;
function Build2() {
var poleDistance : Vector2;
poles.localScale.z = Vector3.Distance(pole1.position,pole2.position); // Find the distance between 2 points
print(poles.localScale.z);
poles.LookAt(pole2);
}

Zoom into group of points in Flex

I have an application in Flex 4 with a map, a database of points and a search tool.
When the user types something and does the search it returns name, details and coordinates of the objects in my database.
I have a function that, when i click one of the results of my search, it zooms the selected point of the map.
The question is, i want a function that zooms all the result points at once. For example if i search "tall trees" and it returns 10 points, i want that the map zooms to a position where i can see the 10 points at once.
Below is the code im using to zoom one point at a time, i thought flex would have some kind of function "zoom to group of points", but i cant find anything like this.
private function ResultDG_Click(event:ListEvent):void
{
if (event.rowIndex < 0) return;
var obj:Object = ResultDG.selectedItem;
if (lastIdentifyResultGraphic != null)
{
graphicsLayer.remove(lastIdentifyResultGraphic);
}
if (obj != null)
{
lastIdentifyResultGraphic = obj.graphic as Graphic;
switch (lastIdentifyResultGraphic.geometry.type)
{
case Geometry.MAPPOINT:
lastIdentifyResultGraphic.symbol = objPointSymbol
_map.extent = new Extent((lastIdentifyResultGraphic.geometry as MapPoint).x-0.05,(lastIdentifyResultGraphic.geometry as MapPoint).y-0.05,(lastIdentifyResultGraphic.geometry as MapPoint).x+0.05,(lastIdentifyResultGraphic.geometry as MapPoint).y+0.05,new SpatialReference(29101)).expand(0.001);
break;
case Geometry.POLYLINE:
lastIdentifyResultGraphic.symbol = objPolyLineSymbol;
_map.extent = lastIdentifyResultGraphic.geometry.extent.expand(0.001);
break;
case Geometry.POLYGON:
lastIdentifyResultGraphic.symbol = objPolygonSymbol;
_map.extent = lastIdentifyResultGraphic.geometry.extent.expand(0.001);
break;
}
graphicsLayer.add(lastIdentifyResultGraphic);
}
}
See the GraphicUtil class from com.esri.ags.Utils package. You can use the method "getGraphicsExtent" to generate an extent from an array of Graphics. You then use the extent to set the zoom factor of your map :
var graphics:ArrayCollection = graphicsLayer.graphicProvider as ArrayCollection;
var graphicsArr:Array = graphics.toArray();
// Create an extent from the currently selected graphics
var uExtent:Extent;
uExtent = GraphicUtil.getGraphicsExtent(graphicsArr);
// Zoom to extent created
if (uExtent)
{
map.extent = uExtent;
}
In this case, it would zoom to the full content of your graphics layer. You can always create an array containing only the features you want to zoom to. If you find that the zoom is too close to your data, you can also use map.zoomOut() after setting the extent.
Note: Be careful if you'Ve got TextSymbols in your graphics, it will break the GraphicUtil. In this case you need to filter out the Graphics with TextSymbols
Derp : Did not see the thread was 5 months old... Hope my answer helps other people

ConcurrentModificationError on Vector

What I am trying to accomplish here is to remove a "blossom" from the Vector whenever a collision is detected. However, I keep getting a ConcurrentModificationError. It messes up when I try to remove the blossom from the Vector. I have tried doing it many ways. At one point when it was detected that the blossom should be removed, I saved its position in the Vector and then tried to remove it when the next position in the list was being looked at. I think this is the only method that you need to see. Can anybody see what I can do to fix this??
private synchronized void DrawBlossoms(Canvas c) // method to draw flowers on screen and test for collision
{
Canvas canvas = c;
for(Blossom blossom: blossomVector)
{
blossom.Draw(canvas);
if (blossom.hit(box_x,box_y, box_x + boxWidth, box_y + boxHeight, blossomVector) == true)
{
Log.v(TAG, "REMOVE THIS!");
//blossomVector.remove(blossom);
}
}
}
The solution is to use an iterator and synchronize on the Vector.
synchronize(blossomVector)
{
Iterator dataIterator = blossomVector.iterator();
while (dataIterator.hasNext())
{
//... do your stuff here and use dataIterator.remove()
}
}

Resources