Apr
2
2013

Inventory Script Test

inventory_script_3D_objects_unity_2

Testing one idea for a inventory system. (free sword from assetstore)

Basic idea is,
– Use the same objects inside the inventory (3D model, with colliders)
– No need to draw icons or to use unity GUI()
– Objects take realistic amount of space, you could even try to fit lots of objects by placing them between others (or maybe later on top of each other, just check for stack maxheight..)
– Maybe later could try even more realistic 3D inventory: 3D bag, objects are rigidbodies that you push/pull inside the bag (and they fall and mix there with physics.. glass objects would break if collision magnitude is > x..)

Webplayer:
http://unitycoder.com/upload/demos/InventoryRealObjects1/

(sound from: http://www.bfxr.net )

Info:
– swords: tag = pickable, layer = pickables)
– ground: tag = ground
– inventory plane: tag = inventory

Source C# (Inventory.cs) :


using UnityEngine;
using System.Collections;

// TODO:
// - add borders to inventory "box"
// - drag from clicked pos, not from pivot (take offset onClick)

public class Inventory : MonoBehaviour {

//private LayerMask mask = -1;
public Transform inventoryPlane;

public dragHelper dragHelperScript;

private bool grabbed = false;
private Transform grabbedObj;
private int layermask = 9; //<< 9;
private int layermaskInverted = 1<< 9;
private Vector3 grabOffset;

private Vector3 origPos;

private Ray ray;
private    RaycastHit hit;

private bool inventoryVisible=true;

void Start ()
{

}

void Update ()
{

// inventory on off
if (Input.GetKeyDown("i"))
{
inventoryVisible = !inventoryVisible;
if (inventoryVisible)
{
inventoryPlane.position -= new Vector3(100,0,0);
}else{
inventoryPlane.position += new Vector3(100,0,0);
}
}

// user clicks
if (Input.GetMouseButtonDown(0))
{
// check for anything pickable
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 50))
{
//float distanceToGround = hit.distance;
if (hit.transform.tag == "pickable")
{
// grab it
//Debug.Log(hit.transform.name);
grabbed = true;
grabbedObj = hit.transform;
//grabbedObj.collider.isTrigger = true;

origPos = grabbedObj.position;

grabOffset = grabbedObj.position-hit.point;

PlaySound(2);

// TODO: if it is inside inventory, then remove helper and rb first..

// create boundingbox? to check for collisions

// add dragChecker script to the object (has onColliderStay())
// add rigidbody, if not exists
if (!grabbedObj.rigidbody)
{
grabbedObj.gameObject.AddComponent("Rigidbody");
}

grabbedObj.rigidbody.useGravity = false;
grabbedObj.rigidbody.constraints = RigidbodyConstraints.FreezeAll;

// add helperscript

//dragHelperScript = grabbedObj.gameObject.AddComponent<dragHelperScript>();
grabbedObj.gameObject.AddComponent("dragHelper");

// reset collision
grabbedObj.gameObject.GetComponent<dragHelper>().isColliding = false;
grabbedObj.gameObject.renderer.material.color = Color.white;

}
}

}

// we are dragging something
if (grabbed)
{

ray = Camera.main.ScreenPointToRay(Input.mousePosition);
//if (Physics.Raycast(ray, out hit, 100, layermask))
if (Physics.Raycast(ray, out hit, 100, layermask))
{
//grabbedObj.position = hit.point+grabbedObj.collider.bounds.size;
grabbedObj.position = hit.point+grabOffset+Vector3.up*grabbedObj.collider.bounds.size.y;

}else{
Debug.Log("some error..");
// drag it near camera..given distance
//Vector3 p = Camera.main.ScreenToWorldPoint(Input.mousePosition)+new Vector3(0,0,10);
//grabbedObj.position = p;
}

}

// dropit
if (Input.GetMouseButtonUp(0))
{

if (!grabbed) return;

// todo: cannot drop if its colliding with 1 or more objects
if (!grabbedObj.gameObject.GetComponent<dragHelper>().isColliding)
{

ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 100, layermask)) // we hit inventory?
{

//Debug.Log(hit.transform.name);

// dropped to inventory
if (hit.transform.tag == "inventory" && grabbed)
{

// add rigidbody, if not exists
if (grabbedObj.rigidbody)
{
Destroy (grabbedObj.rigidbody);
//                            grabbedObj.gameObject.AddComponent("Rigidbody");
}

//                        grabbedObj.rigidbody.useGravity = true;
//                        grabbedObj.rigidbody.constraints = RigidbodyConstraints.FreezeAll;
//grabbedObj.rigidbody.isKinematic = true;

grabbedObj.parent = inventoryPlane;

// reset collision (reset from other also?)
//                        grabbedObj.gameObject.GetComponent<dragHelper>().isColliding = false;
//                        grabbedObj.gameObject.renderer.material.color = Color.white;

//Destroy (grabbedObj.gameObject.GetComponent<dragHelper>());

//grabbedObj.collider.isTrigger = false;
grabbed = false;
grabbedObj = null;

PlaySound(1);

}

// drop to ground
if (hit.transform.tag == "ground" && grabbed)
{
Debug.Log("1");
origPos = hit.point+Vector3.up*grabbedObj.collider.bounds.size.y;
dropBack();
}

}else{ // not hitting good object
// cannot drop here
dropBack();
}
}else{
//    Debug.Log(2);
dropBack();
}
}

}

void dropBack()
{
// remove from inventory (if it was there)
grabbedObj.parent = null;

// restoro position, drag failed..
grabbedObj.position = origPos;

grabbedObj.gameObject.GetComponent<dragHelper>().isColliding = false;
grabbedObj.gameObject.renderer.material.color = Color.white;

// remove rb
Destroy (grabbedObj.rigidbody);

grabbed = false;
grabbedObj = null;

PlaySound(1);

// restore colors?

// remove helper script

}

void PlaySound(int type)
{
// TODO: different types..ring, bottle, metal..

audio.pitch = type;
audio.Play();

}

}

dragHelper.cs

using UnityEngine;
using System.Collections;

public class dragHelper : MonoBehaviour {

    public bool isColliding=false;
    public Transform other;
    
    void OnCollisionEnter(Collision collisionInfo) 
    {
        
        // fx
        // set color
        if (collisionInfo.transform.tag != "inventory" && collisionInfo.transform.tag != "ground")
        {    
            isColliding = true;
            other = collisionInfo.transform;

            renderer.material.color = Color.red;
        }
        
    }    
    
    void OnCollisionStay(Collision collisionInfo) 
    {
        //if (collisionInfo.transform.tag != "inventory")
            //Debug.Log("we are hittingh..");
//        other = collisionInfo.transform;
//        isColliding = true;
    }

    void OnCollisionExit(Collision collisionInfo) 
    {
//        print("No longer in contact with " + collisionInfo.transform.name);
        if (collisionInfo.transform.tag != "inventory" && collisionInfo.transform.tag != "ground")
        {
            renderer.material.color = Color.white;
            isColliding = false;
            other = collisionInfo.transform;
        }
    }
    
    // TODO: use some other way..?
    void Update()
    {
        if (rigidbody)
            rigidbody.WakeUp();
    }
    
}



9 Comments + Add Comment

Leave a comment

Connect

Twitter View LinkedIn profile Youtube Youtube Join Discord Twitch Instagram

UnityLauncherPro

Get UnityLauncherPRO and work faster with Unity Projects!
*free unity hub alternative

@unitycoder_com

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.