Question

Allright, so I am making a mobile 2d building game. where you can drag a rectangle or circle from your inventory in the game.

how I would like it to be set up: on the top or right side is an inventory with objects/textures, when I drag one of the items from my inventory into the game. it then removes the item from the inventory. after that the items inventory will all move 1 slot up. so that the first slot is allways occupied.

How would I make this work? can someone please help me think or give me some examples?

Thanks in advance!

Était-ce utile?

La solution

First you need to draw an image for the item in the inventory. I have done this before with an GUI Button with an image attached to it. Here is an example in C#:

void OnGUI(){
    if (GUI.Button(new Rect(0, 0 , 10, 10), itemTexture,))
    {
    //The if here is to get when the image get pushed.
    //Push the item to the world
    }
}

When the player clicks on the item you must push it to the world. You can do that with this code:

private Vector3 mousePositionInWorld = Camera.main.ScreenToWorldPoint(Input.mousePosition);
private Object block = Instantiate(objectYouClicked, new Vector3(mousePositionInWorld.x, mousePositionInWorld.y, 0), Quaternion.identity);

The object must be bound to the player mouse/touch position. You can make the object bound to the player with this code:

private Vector3 screenPoint;
void OnMouseDown()
{
    screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
}

void OnMouseDrag()
{
      Vector3 currentScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
      Vector3 currentPos = Camera.main.ScreenToWorldPoint(currentScreenPoint);
      rigidbody.MovePosition(currentPos);
}

So for example you have an inventory object. Like this:

void OnGUI(){
    if (GUI.Button(new Rect(0, 0 , 10, 10), itemTexture,))
    {
        private Vector3 mousePositionInWorld = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        private Object block = Instantiate(objectYouClicked, new Vector3(mousePositionInWorld.x, mousePositionInWorld.y, 0), Quaternion.identity);
    }
}

Then you have an prefab/object with an script attached that contains this code:

private Vector3 screenPoint;
void OnMouseDown()
{
    screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
}

void OnMouseDrag()
{
      Vector3 currentScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
      Vector3 currentPos = Camera.main.ScreenToWorldPoint(currentScreenPoint);
      rigidbody.MovePosition(currentPos);
}

This way when the player clicks and holds the mousebutton on the object the position is changed to the mouseposition.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top