- Home /
This question was
closed Jun 05, 2018 at 03:32 PM by
MilkyTheCarton for the following reason:
Problem is not reproducible or outdated
Question by
MilkyTheCarton · May 11, 2018 at 04:30 PM ·
collider2d2d-physicslinerendererbounceraycasthit2d
How can i shoot 2D ball/bounce of wall using Raycast?
Hello fellow traveler, i am trying to shoot a ball and be able to bounce of wall and keep going like in Puzzle Bubble/Pool games.
My shooting code, Cannon.cs:
void Update () {
// Raycast code
if( fireRate == 0)
{
if (Input.GetButtonDown("Fire1"))
{
Shoot();
}
}
else
{
if (Input.GetButton("Fire1") && Time.time> timeToFire)
{
timeToFire = Time.time + 1 / fireRate;
Shoot();
}
}
}
//Raycast code
void Shoot()
{
Vector2 mousePosition = new Vector2(Camera.main.ScreenToWorldPoint(Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y);
Vector2 firePointPosition = new Vector2(bullet.position.x, bullet.position.y);
Vector2 val = mousePosition - firePointPosition;
RaycastHit2D hit = Physics2D.Raycast(firePointPosition, val, 100, notToHit);
Effect();
Debug.DrawLine(firePointPosition, (mousePosition-firePointPosition)*100, Color.cyan);
if(hit.collider != null)
{
Debug.DrawLine(firePointPosition, hit.point, Color.red);
//Debug.Log("We hit " + hit.collider.name);
if(hit.collider.GetComponent<BoxInteraction>() != null)
{
hit.collider.GetComponent<BoxInteraction>().beenHit();
}
}
}
With the current code i am able to hit the boxes, i use the Debug.DrawLine for testing, check what i'm hitting and whatnot.
Now i am stuck at how i can simulate shooting 1 ball at a time and it being able to bounce of the wall and creating an aim line so i can know where it will hit before shooting like in Pool games.
Can it be done using Raycast? If yes, how?
Any nudge in the right direction its very much appreciated.
~Milky
4.png
(62.1 kB)
Comment
Answer by tormentoarmagedoom · May 11, 2018 at 07:01 PM
Good day.
The best way is Instantiate a ball with a collider, and detect with what element is the collision with
OnColliderEnter (Collision TheOtherObject)
{
}
bye!
Okay, if i use this method for going at it then how can i make the ball bounce of the wall and hit a specific point where i am ai$$anonymous$$g? Also this doesn't answer another part of my original question, how can i use Raycast to simulate ai$$anonymous$$g line, like Puzzle Bubble/Pool table games?