How to convert a tile layer into an object for depth sorting relative to the player? - gml

I'm essentially making a Stardew Valley clone, using tile sets and tile layers to draw the background of each room. I have a 'Parent Depth Object'. Each child of this object (NPC's, crops) has its depth sorted relative to the player object to appear in front or behind the player. This works fine.
I have 'ground items' (barrels, rocks etc.) drawn to a single tile layer in each room. I want the player to be able to appear behind or in front of these too. Is there any way I can make this whole layer act as if it was a single object so I can add it to my Parent Depth Object, or do I have to create a separate object for each ground item?
My 'depthSorter' object creates a Data Structure, adds each instance to it and loops through, sorting the depth of each relative to the player.
/// #description DSGridGetInst/Add/Sort/Loop
// get number of instances of parentDepthObject, save in variable instNum / resize grid
var instNum = instance_number(parentDepthObject);
var dGrid = dsDepthGrid;
ds_grid_resize(dGrid, 2, instNum);
// add instances to grid / have all of them run this code
var yy = 0; with(parentDepthObject)
{
dGrid[# 0, yy] = id;
dGrid[# 1, yy] = y;
yy += 1;
}
// sort the grid in ascending order (lowest y value at top)
ds_grid_sort(dGrid, 1, true);
// loop through the grid and draw all the instances
var inst; yy = 0; repeat(instNum)
{
// pull out an ID
inst = dGrid[# 0, yy];
// draw yourself
with(inst)
{
event_perform(ev_draw, 0);
}
yy += 1;
}

I'd personally recommend to use these items you want to get behind as objects, rather than tiles. Tiles can't contain a script themselves. So that gets more tricky to use them the way you want.
However, you don't need to create a new object for each 'ground item'.
Instead, you can make an object called 'ground item', and change the sprite / related code to that object.
For example, when selecting an object in a room, you can use 'Creation Code' to add code that's unique for that object. That way, you can change the sprites of the ground item to it's unique id.
Another example is to make an object that's a child of the parent 'ground object'. So each object has it's own sprite, but reuses the object from 'ground object'

Related

DateTime as ordering key in oxyplot LineSeries

Is there a way to tell oxyplot to use the x value as the connect/draw order for a line plot instead of the order that the points are added?
Let's assume I have this huge amount of points (2Gb in RAM) of a time series. At a higher level I am only adding a small percentage of those points and as the user zooms into a more specific region I add more points to the series so he can see more detail. Almost like a texture mimap. I can add all the points at once but then oxy becomes really slow when I tries to render all those points in a single window in WPF Maybe there is another solution here?
The problem that I am facing is that oxy draws a line from the last point in the graph to the first one of the new batch because it uses the series points list as the draw order not the X value. Is there a way to change this?
Here is a tiny example based on the 'WPF Simple Example':
var plotModel = new PlotModel { Title = "Simple example", Subtitle = "using OxyPlot" };
var timeAxis = new DateTimeAxis
{
Position = AxisPosition.Bottom,
StringFormat = "hh:mm:ss",
};
plotModel.Axes.Add(timeAxis);
var now = DateTime.UtcNow;
// Create two line series (markers are hidden by default)
var series1 = new LineSeries { Title = "Series 1", MarkerType = MarkerType.Circle };
series1.Points.Add(new DataPoint(DateTimeAxis.ToDouble(now), 5));
series1.Points.Add(new DataPoint(DateTimeAxis.ToDouble(now.AddMinutes(1)), 7));
series1.Points.Add(new DataPoint(DateTimeAxis.ToDouble(now.AddMinutes(2)), 8));
series1.Points.Add(new DataPoint(DateTimeAxis.ToDouble(now.AddMinutes(0.5)), 10));
// Add the series to the plot model
plotModel.Series.Add(series1);
// Set the Model property, the INotifyPropertyChanged event will make the WPF Plot control update its content
this.Model = plotModel;
Here is the output, note that the line draws "back in time":
Is there a solution that does not involves me sorting the points list (not even sure if this works)?
Or maybe I am doing this extra points for details thing completely wrong :)

Hiding the still objects when another createjs object passes through them in createjs

is there a way to hide the objects through which another object is passing in createjs. Also i have defined a path for the moving object but when it crosses other objects that come in the path; the objects are not hidden. It gives the view as if the moving object is cutting other objects. Is there a way in createjs through which i can handle this situation?
Sure, there is a way for that. You can calculate the area of the intersection between 2 objects, and if it's a number higher than 0, then you can hide the second object. It will look something like this:
var bounds1 = object1.nominalBounds; //or .getBounds();
var bounds2 = object2.nominalBounds;
var rectangle = bounds1.intersection(bounds2);
if (rectangle != null && rectangle.width * rectangle.height > 0){
object2.visible = false;
}
That's the gist of it, although depending on your objects and their containers, it might be a little more complicated than this, like needing to translate their coordinates to a global scope.

How to make large 2d tilemap easier to load in Unity

I am creating a small game in the Unity game engine, and the map for the game is generated from a 2d tilemap. The tilemap contains so many tiles, though, is is very hard for a device like a phone to render them all, so the frame rate drops. The map is completely static in that the only moving thing in the game is a main character sprite and the camera following it. The map itself has no moving objects, it is very simple, there must be a way to render only the needed sections of it or perhaps just render the map in once. All I have discovered from researching the topic is that perhaps a good way to do it is buy using the Unity mesh class to turn the tilemap into a mesh. I could not figure out how to do this with a 2d tilemap, and I could not see how it would benefit the render time anyways, but if anyone could point me in the right direction for rendering large 2d tilemaps that would be fantastic. Thanks.
Tile system:
To make the tile map work I put every individual tile as a prefab in my prefab folder, with the attributes changed for 2d box colliders and scaled size. I attribute each individual prefab of the tile to a certain color on the RGB scale, and then import a png file that has the corresponding colors of the prefabs where I want them like this:
I then wrote a script which will place each prefab where its associated color is. It would look like this for one tile:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Map : MonoBehaviour {
private int levelWidth;
private int levelHeight;
public Transform block13;
private Color[] tileColors;
public Color block13Color;
public Texture2D levelTexture;
public PlayerMobility playerMobility;
// Use this for initialization
void Start () {
levelWidth = levelTexture.width;
levelHeight = levelTexture.height;
loadLevel ();
}
// Update is called once per frame
void Update () {
}
void loadLevel(){
tileColors = new Color[levelWidth * levelHeight];
tileColors = levelTexture.GetPixels ();
for (int y = 0; y < levelHeight; y++) {
for (int x = 0; x < levelWidth; x++) {
// if (tileColors [x + y * levelWidth] == block13Color) {
// Instantiate(block13, new Vector3(x, y), Quaternion.identity);
// }
//
}
}
}
}
This results in a map that looks like this when used with all the code (I took out all the code for the other prefabs to save space)
You can instantiate tiles that are in range of the camera and destroy tiles that are not. There are several ways to do this. But first make sure that what's consuming your resources is in fact the large number of tiles, not something else.
One way is to create an empty parent gameObject to every tile (right click in "Hierarchy" > Create Empty"
then attach a script to this parent. This script has a reference to the camera (tell me if you need help with that) and calculates the distance between it and the camera and instantiates the tile if the distance is less than a value, otherwise destroys the instance (if it's there).
It has to do this in the Update function to check for the distances every frame, or you can use "Coroutines" to do less checks (more efficient).
Another way is to attach a script to the camera that has an array with instances of all tiles and checks on their distances from the camera the same way. You can do this if you only have exactly one large tilemap because it would be hard to re-use this script if you have more than a large tilemap.
Also you can calculate the distance between the tile and the character sprite instead of the camera. Pick whichever is more convenient.
After doing the above and you still get frame-drops you can zoom-in the camera to include less tiles in its range but you'd have to recalculate the distances then.

constrain proportions while resizing images

I implemented drag and drop of images and now i want to constrain proportions of images while resizing.
/**
* Variable: constrainChildrenOnResize
*
* Specifies if children should be constrained according to the <constrainChildren>
* switch if cells are resized (including via <foldCells>). Default is false for
* backwards compatiblity.
*/
mxGraph.prototype.constrainChildrenOnResize = false;
i set this to true but its not working :s
What API/property i need for this functionality..
constrainChildrenOnResize is responsible for positioning and size of the children of resized cell. It means that children should keep their position relatively to the parent-cell.
In your case I would suggest to extend mxVertexHandler using union method. In this example you can see how to implement min-width/min-height restrictions. Using this example you are able to write your own rules for constrain.
Here is my simple solution:
var vertexHandlerUnion = mxVertexHandler.prototype.union;
mxVertexHandler.prototype.union = function (bounds) {
var result = vertexHandlerUnion.apply(this, arguments);
var coff = bounds.width / bounds.height
result.width = result.height * coff;
return result;
};
So this function is called every time you move mouse during dragging the resizer.
bounds - object, always same and represent old geometry of the cell (before resizing)
result - object, represents new values, which are going to be applied. Between this line ad return statement you can place any code you need to modify result.
In my simple example I just get the initial relation between width and height of the cell (coff) and then set new width by multiplying coff and new height. It will work if you drag corner or top/bottom. In real project this logic should be slightly extended, or you should make visible only corner handlers.
By the way, this code will work for all resizable cells on your graph. If you want to apply it only to images or some other kind of cells - you can put condition and check the cell type before recalculating. You can get current cell or its state via this.state.cell or this.state inside of union function.
For example only for vertecies:
... ...
var result = vertexHandlerUnion.apply(this, arguments);
if (this.state.cell.isVertex()) {
//calculations here
}
return result;

Problems in my AS2 Game

Hey guys, I'm trying to make a 2D Platform style game similar to this game below:
http://www.gameshed.com/Puzzle-Games/Blockdude/play.html
I have finished making most of the graphic, and areas, and collision, but our character is still not able to carry things. I'm confused as to what code to use so that my character can carry the blocks. I need help as to how to make our character carry blocks that are in front of him, provided that the blocks that don't have anything on top of it. This has been confusing me for a week now, and any help would be highly appreciated. :D
I fondly remember my first AS2 game. The best approach is probably an object oriented approach, as I will explain.
In AS2, there is a hittest method automatically built into objects. There is a good tutorial on Kirupa here:
http://www.kirupa.com/developer/actionscript/hittest.htm
also
http://help.adobe.com/en_US/AS2LCR/Flash_10.0/help.html?content=00001314.html
First you'll want to generate your boxes using a Box class. Your class would need to look something like the following:
//Box.as pseudo-code
class Box {
var x_pos:Number;
var y_pos:Number;
var attachedToPlayer:Boolean;
function Box(_x:Number, _y:Number) {
this.x_pos = _x;
this.y_pos = _y;
}
//other code here
}
See this tutorial on how to attach a class to an object in the library:
http://www.articlesbase.com/videos/5min/86620312
To create a new Box, you'd then use something like
box1 = new Box(100,200);
// creates a box at position 100x,200y
However, you'll also want to store the blocks you want to pickup into some sort of array so you can loop through them. See http://www.tech-recipes.com/rx/1383/flash-actionscript-create-an-array-of-objects-from-a-unique-class/
Example:
//somewhere near the top of your main method, or whereever your main game loop is running from - note Box.as would need to be in the same folder
import Box;
//...then, somewhere before your game loop
//create an array to hold the objects
var boxArray:Array = new Array();
//create loop with i as the counter
for (var i=0; i<4; i++)
{
var _x:Number = 100 + i;
var _y:Number = 100 + i;
//create Box object
var box:Box = new Box();
//assign text to the first variable.
//push the object into the array
boxArray.push(box);
}
Similarly, you would need a class for your player, and to create a new Player object at the start of your game, e.g.
var player = new Player(0,0);
You could then run a hittest method for your player against the blocks in your array for the main game loop (i.e. the loop that updates your player's position and other game properties). There are probably more efficient ways of doing this, e.g. only looping for the blocks that are currently on the screen.
Once your array has been created, use a foreach loop to run a hittest against your player in your game's main loop, e.g.
//assuming you have an array called 'boxArray' and player object called 'player'
for(var box in boxArray){
if (player.hittest(box)) {
player.attachObjectMethod(box);
}
}
This is basically pseudo-code for "for every box that we have entered into the array, check if the player is touching the box. If the box is touching, use the box as the argument for a method in the player class (which I have arbitrarily called attachObjectMethod)".
In attachObjectMethod, you could then define some sort of behavior for attaching the box to the player. For example, you could create a get and set method(s) for the x and y position of your boxes inside the box class, along with a boolean called something useful like attachedToPlayer. When attachObjectMethod was called, it would set the box's boolean, e.g. in the Player class
//include Box.as at the top of the file
import Box;
//other methods, e.g. constructor
//somewhere is the Player.as class/file
public function attachObjectMethod (box:Box) {
box.setattachedToPlayer(true);
//you could also update fields on the player, but for now this is all we need
}
Now the attachedToPlayer boolean of the box the player has collided with would be true. Back in our game loop, we would then modify our loop to update the position of the boxes:
//assuming you have an array called 'boxArray' and player object called 'player'
for(var box in boxArray){
if (player.hittest(box)) {
player.attachObjectMethod(box);
}
box.updatePosition(player.get_Xpos, player.get_Ypos);
}
In our Box class, we now need to define 'updatePosition':
//Box.as pseudo-code
class Box {
var x_pos:Number;
var y_pos:Number;
var attachedToPlayer:Boolean;
function Box(box_x:Number, box_y:Number) {
this.x_pos = box_x;
this.y_pos = box_y;
}
public function updatePosition(_x:Number, _y:Number) {
if (this.attachedToPlayer) {
this.x_pos = _x;
this.y_pos = _y;
}
}
//other code here
}
As you can see we can pass the player's position, and update the box's position if the attachedToPlayer boolean has been set. Finally, we add a move method to the box:
public function move() {
if (this.attachedToPlayer) {
this._x = x_pos;
this._y = y_pos;
}
}
Examples of updating position:
http://www.swinburne.edu.au/design/tutorials/P-flash/T-How-to-smoothly-slide-objects-around-in-Flash/ID-17/
Finally, to make it all work we need to call the move method in the game loop:
//assuming you have an array called 'boxArray' and player object called 'player'
for(var box in boxArray){
if (player.hittest(box)) {
player.attachObjectMethod(box);
}
box.updatePosition(player.get_Xpos, player.get_Ypos);
box.move();
}
You have also specified that the blocks should only move with the player if they have nothing on top of them. When you call your attachedToPlayer method, you would also need to run a foreach loop inside the method between the box and the objects that might sit on top of the box. You should now have a fair idea from the above code how to do this.
I appreciate that this is quite a lengthy answer, and I haven't had an opportunity to test all the code (in fact I'm fairly positive I made a mistake somewhere) - don't hesitate to ask questions. My other advice is to understand the concepts thoroughly, and then write your own code one bit at a time.
Good luck!
The way I would do this is to design an individual hit test for each block he will be picking up, then code for the hit test to play a frame within the sprite's timeline of him carrying a block, and to play a frame within the block to be picked up's timeline of the block no longer at rest (disappeared?).
Good Luck if you're confused about what I've said just ask a little more about it and I'll try to help you if I can.