Question by
Bocksdin · Feb 16, 2018 at 03:20 AM ·
object move
Player and AI throw ball - C#
I'm sure this is already answered correctly somewhere, but I can't seem to find it. I have tried a number of remedies already. I have a "Player" game object made from a primitive capsule, a few AI capsules moving randomly on two different teams (red and blue), and several primitive spheres for throwing at each other. When the player is holding a ball and clicks I need the ball to move to the click position over time. When the AI is holding a ball, it waits a random amount of time, chooses a random enemy target and throws the ball at the enemy target's position at the time the ball was thrown. However, when the player or AI try to throw the ball it doesn't go anywhere.
private bool canHold = true;
public GameObject ball;
public Transform guide;
private float speed = 10; //Speed multiplier for the ball throw
private GameObject[] targetList;
private Vector3 mouseClick;
void Update()
{
AIThrow();
if (Input.GetMouseButtonUp(0))
{
mouseClick = Input.mousePosition;
PlayerThrow();
}
}
private void OnTriggerEnter(Collider other)
{
if (other.tag == "OnGround")
{
if (!ball)
{
ball = other.gameObject;
Pickup();
}
}
}
private void Pickup()
{
if (!ball)
{
return;
}
ball.transform.SetParent(guide);
ball.transform.position = guide.position;
canHold = false;
ball.tag = this.tag + "Ball";
}
private void PlayerThrow()
{
//On click, throw the ball the "Player" object is holding...
//...to the click position
if (!ball)
{
return;
}
ball.transform.position = Vector3.MoveTowards(ball.transform.position, mouseClick, speed * Time.deltaTime);
ball.tag = this.tag + "InAir";
ball = null;
}
private void AIThrow()
{
float waitTime = Random.Range(1,5); //Wait for 1-4 seconds to throw a ball after picking one up
float waitTimePassed = 0;
int index;
GameObject randomTarget; //Choose random enemy "Red" tag or "Blue" tag target for ball throw
if (!ball)
{
return;
}
waitTimePassed += Time.deltaTime;
if (this.name == "RedPlayer")
{
targetList = GameObject.FindGameObjectsWithTag("Blue");
} else if (this.name == "BluePlayer")
{
targetList = GameObject.FindGameObjectsWithTag("Red");
}
index = Random.Range(0, targetList.Length);
randomTarget = targetList[index];
if (waitTimePassed >= waitTime)
{
ball.transform.position = Vector3.MoveTowards(ball.transform.position, randomTarget.transform.position, speed * Time.deltaTime);
ball.tag = this.tag + "InAir";
ball = null;
}
}
Comment