- Home /
How to pick up an Item in 2D
so i made a script where when i press "e" the item gets destroyed, but now i don't know how to get it into the players Hands.
private bool pickUpAllowed;
// Use this for initialization
private void Start () {
}
// Update is called once per frame
private void Update () {
if (pickUpAllowed && Input.GetKeyDown(KeyCode.E))
PickUp();
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.name.Equals("Girl"))
{
pickUpAllowed = true;
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject.name.Equals("Girl"))
{
pickUpAllowed = false;
}
}
private void PickUp()
{
Destroy(gameObject);
}
}
Answer by andycodes · Jan 11, 2021 at 05:27 PM
There are a few ways you could tackle this:
Instead of deleting the object, you could instead make the player's hand the parent of the object you want to pick up, and set the local position and rotation appropriately to look nice in the players hands. You might also want to disable the collision or trigger depending on your implementation.
Create a dummy object that always exists as a child of the player's hand, and when you pick something up, just place the sprite of the pickup object as the sprite of the object in the player's hands. This could probably be refined to account for object scale.
The second method might not be as viable depending on what you plan to do with the object: if the object is, say, a sword, you'd want information about the sword like the attack speed, or how much damage it inflicts. In this situation, the first approach might be preferable.
Answer by logicandchaos · Jan 11, 2021 at 07:25 PM
You can parent it to the player and set it on the correct localePosition, then it will move with your player, if that is what you want, to put it down you would have to unparent or destroy it.
Answer by unity_En9Jz88Uh8XLKA · Jan 12, 2021 at 08:41 AM
Thanks to both of you for your fast answer! But I am a total noob and I tried to do this. But it doesn't work. I don't know how to write that code. Sorry for asking this but how would that code look like.
You can parent it to the player and set it on the correct localePosition
This can be done like:
PickedUpObject.transform.SetParent(Player.transform);
PickedUpObject.transform.position = HandPosition;
when you pick something up, just place the sprite of the pickup object as the sprite of the object in the player's hands.
Can be done by changing the sprite on the sprite renderer:
PlayerHand.GetComponent<SpriteRenderer>().sprite = PickedUpObject.GetComponent<SpriteRenderer>().sprite;
Your answer
Follow this Question
Related Questions
Lerpz 2D Tutorial - Can't Save Scene And Proceed 0 Answers
2D Platformer Level Design 0 Answers
How do I edit the first person controller to work with android? 0 Answers
2d Game with 3d Objects 0 Answers