- Home /
Problem with prefabs and offset
Hi, I'm having a simple problem trying to generate a basic 2d tiled map out of 2 prefabs and a player.
Basically, everything seems to have a 0.5 offset so the player can't collide properly with the walls and the floor tiles don't align properly either.
Notice on the screenshot how, with the mouse located at the green dot, the onHover property of the wall is being triggered, and both the player and the floor tiles are not aligning properly (but it seems that the other kind of floor is, but they don't have boxcolliders).
The sprite seems to be 0.5 to the right and 0.5 upwards. The boxcollider property of the wall prefab is set to 0,0,0.
This is my map generation script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MapManager : MonoBehaviour {
public int width;
public int height;
public GameObject[] floorTiles;
public GameObject[] mapBorderTiles;
private Transform mapHolder;
private List <Vector3> gridPositions = new List<Vector3>();
void BoardSetup(){
mapHolder = new GameObject ("Map").transform;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
GameObject toInstantiate = floorTiles [Random.Range (0, floorTiles.Length)];
if(x == 0 || x == width - 1 || y == 0 || y == height - 1){
toInstantiate = mapBorderTiles[Random.Range (0, mapBorderTiles.Length)];
}
GameObject instance = Instantiate(toInstantiate, new Vector3(x, y, 0f), Quaternion.identity) as GameObject;
instance.transform.SetParent(mapHolder);
}
}
}
public void setupMap(){
BoardSetup ();
}
}
And this are my wall prefab settings.
EDIT
Ok I'm a complete beginner in Unity but the problem was quite simple. I was treating the position of the player as a point on its sprite's top left vertex and by default it is on the center, so I was always going to be half a sprite off because of my player initialization (int, int, int instead of float, such as 8.5f).
The player now works properly WITHOUT a BoxCollider2d offset, but the offset it is still needed for the wall prefabs.
Is there any way I could further simplify this? Code wise, it is easier to think the prefabs as points on the top-left vertex..
Thanks
Answer by jdean300 · Jan 15, 2018 at 03:23 AM
It seems like you need to check the import settings of the sprite to see where the pivot point of that sprite is located. Failing that, you can change the wall prefab so that what you have currently is under another object and change the position of the child object to have the position of the object located at the center of the tile or wherever it is you need it to be. Check the sprite pivot point settings first.
The pivot doesn't seem to be the problem, see:
I didn't quite get the other option.