- Home /
Can i have help writing a script to pick up and throw a ball (2D game)
there are 10 balls, and 3 players in play, and I am needing help fixing my script for one of the player objects to pick up and be able to throw a ball whenspace is pressed. I will put what I have so far, thank you for anyone who tries to help. Oh and this is a 2D game by the way.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallThrow : MonoBehaviour
{
private bool ballInHands = false;
public float ballSpeed;
private Rigidbody2D ballRB;
public float offset;
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Ball")
{
if (ballInHands == false)
{
ballInHands = true;
other.gameObject.transform.position = transform.position + new Vector3(transform.position.x, transform.position.y + offset, transform.position.z);
if (Input.GetKeyDown("space"))
{
ballRB = other.GetComponent<Rigidbody2D>();
ballRB.AddForce(transform.up);
ballInHands = false;
}
}
}
}
}//end of class
Answer by Cuttlas-U · Oct 04, 2017 at 03:58 AM
hi;
i think u did a good job and u have some mistakes;
first of all pay attention to this code u wrote :
this has an if statement that is waiting for the player to press a button ; but this code is in trigger function and it will be checked just once , while u need to check every fram for player input;
so u can make a bool and put this in update function ; another change im doing is adding ,ForceMode2D.Impulse to your force code ; so check for what it does;
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Ball")
{
if (ballInHands == false)
{
ballInHands = true;
other.gameObject.transform.position = transform.position + new Vector3(transform.position.x, transform.position.y + offset, transform.position.z);
}
}
}
void Update()
{
if ( ballInHands == true )
{
if (Input.GetKeyDown("space"))
{
ballRB = other.GetComponent<Rigidbody2D>();
ballRB.AddForce(transform.up,ForceMode2D.Impulse);
ballInHands = false;
}
}
}
The script you posted just does what $$anonymous$$e did, send the ball left and up about 1 meter. Then nothing else, the player can still move but the ball just stays there, But I did fix an error in the code you posted when you try to reference other.gameObject I update() its out of reference since the variable is a constructor for OnTriggerEnter, the way I fixed this is by assigning ballRB to other.gameObject in the OnTriggerEnter function. But I still cannot solve my other error. Thank you for helping me though!