Skip to content

Instantly share code, notes, and snippets.

@adadesions
Created June 22, 2023 06:16
Show Gist options
  • Select an option

  • Save adadesions/577a16d762f8d95de8bbada0062cdea9 to your computer and use it in GitHub Desktop.

Select an option

Save adadesions/577a16d762f8d95de8bbada0062cdea9 to your computer and use it in GitHub Desktop.

Revisions

  1. adadesions created this gist Jun 22, 2023.
    68 changes: 68 additions & 0 deletions PlayerGrabItem.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,68 @@
    using System;
    using Games.MiniGame.GCD_Game.Scripts.Items;
    using Paideria.Minigames.GCD;
    using UnityEngine;

    namespace Games.MiniGame.GCD_Game.Scripts.Player
    {
    public class PlayerGrabItem : MonoBehaviour, IGrabItemByPlayer
    {
    [SerializeField] private Vector3 offset;
    [SerializeField] Vector3 _throwingForce;
    [SerializeField] float _launchAngle = 45.0f;
    private float _launchAngleRad;
    private Vector3 _throwVelocity;
    private GameObject _holdingItem;


    // Start is called before the first frame update
    void Start()
    {
    _holdingItem = null;
    }

    // Update is called once per frame
    void Update()
    {
    ItemMovingWithPlayer();
    }

    private void ItemMovingWithPlayer()
    {
    if (_holdingItem == null) return;

    try {
    bool isHolding = _holdingItem.GetComponent<GrabableItem>().IsHolding;
    if (_holdingItem && isHolding) {
    _holdingItem.transform.position = transform.position + offset;
    }
    } catch (Exception) {
    _holdingItem = null;
    }

    }

    public void PlayerHoldItem(GameObject item)
    {
    _holdingItem = item;
    _holdingItem.transform.position = transform.position + offset;
    }

    public void PlayerThrowItem()
    {
    _launchAngleRad = _launchAngle * Mathf.Deg2Rad;
    _throwVelocity = new Vector3(
    _throwingForce.z * Mathf.Cos(_launchAngleRad),
    _throwingForce.y * Mathf.Sin(_launchAngleRad),
    0f
    );

    var rb = _holdingItem.GetComponent<Rigidbody>();
    var horizontalComponent= _throwingForce.z * transform.forward;
    var verticalComponent = _throwingForce.y * Vector3.up;
    var forceVector = horizontalComponent + verticalComponent;
    rb.AddForce(forceVector, ForceMode.Impulse);
    _holdingItem = null;
    }
    }
    }