Hi, I am making a sports game and I need help with the code.
I want it so if the player presses the G key they grab and when grabbing they can throw.
This script is on the collider of the Player.
There I have 2 booleans: throwing and grabbing
Here is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GrabZonePlayer1 : MonoBehaviour
{
[SerializeField] Transform ball;
[SerializeField] Player1 player;
[SerializeField] Vector2 ballPlayerVector;
[SerializeField] GameObject Hands;
[SerializeField] float powerX;
[SerializeField] float powerY;
bool grabbing;
bool throwing;
void Start()
{
ballPlayerVector = ball.transform.position - player.transform.position;
grabbing = false;
throwing = false;
}
void Update()
{
if (Input.GetKeyDown(KeyCode.G))
{
if (grabbing == true)
{
throwing = true;
ball.transform.position = Hands.transform.position;
ball.transform.parent = Hands.transform;
}
if(throwing == true)
{
if (Input.GetKeyDown(KeyCode.T))
{
grabbing = false;
ball.GetComponent<Rigidbody2D>().velocity = new Vector2(powerX, powerY);
}
}
}
}
private void OnTriggerEnter2D(Collider2D other)
{
if(other.tag == "Ball")
{
grabbing = true;
}
}
}
Thanks.