So I had this idea which is very straightforward in theory of how to tell if a multi-dimensional item can fit in a certain inventory region or not. Take a 2x2 item for ex, I divide it into 4 equal sections, take the center of each section and cast a ray from that center towards the inventory, if all 4 rays intersect with empty slots, then the item can fit, otherwise not. Here’s what I mean:
The first item doesn’t fit, cause there’s one square intersecting with an occupied slot. The second item fits, there’s nothing in its way.
One detail I forgot to mention is that, I don’t do this when I pickup an item, instead I just find the first available region for the item to fit in and add it. I do the raycasting thing when I’m holding an item with the mouse and want to place it somewhere else (player could hold the item, rotate it, swap etc)
So I figured it out, all I needed to know was that there’s a RaycastAll(PointerEventData, List<RaycastResult) in EventSystem and that I need to instantiate an event data and set its position where I want the raycast to be, in my case it’s the center of each item division
bool DoesItemFit(Item item)
{
var pos = item.InvRepresentation.transform.position;
var system = EventSystem.current;
var hits = new List<RaycastResult>();
var pointer = new PointerEventData(system);
float width = slotSize.x;
float height = slotSize.y;
int nHits = 0;
for(int i = 0; i < item.nRowsRequired; i++)
{
float y = (height / 2) + (height * i);
for(int j = 0; j < item.nColsRequired; j++)
{
float x = (width / 2) + (width * j);
pointer.position = new Vector2(pos.x + x, pos.y - y);
system.RaycastAll(pointer, hits);
for(int k = 0; k < hits.Count; k++)
{
var hit = hits[k];
var go = hit.gameObject;
var slot = go.GetComponent<Slot>();
if (slot != null)
{
if (!slot.IsEmpty)
return false;
nHits++;
}
}
}
}
return nHits == item.nRowsRequired * item.nColsRequired;
}
this is super cool! i dont quite understand how the eventSystem works and what it is capable of, but i’m trying to achieve multitouch to instantiate 2 joysticks for a top-down duel shooter for mobile devices. i’m using ray cast code to try and spawn in the joysticks but UGUI cant be effected by ray-casts apparently and there is no multitouch functionality to the eventSystem that i know of.
Hi! - Check Touch class from scripting manual, it works with multi touch, however, Input class / EventSystem only works with single click in Editor.
And you can’t basically “click” on empty space around your joystick, I’ve got hard time figuring my way around this thinking - I guess the best way is to have sort of spawn script, on empty area with transparent Image component, click on this area spawns/unhide your joystick.
And definitely cool thread - funny I searched for raycasting UI and found this thread just 2 hours ago too.