# Shooting Mechanic in 2D Mobile (Unity C#)

Hello

I’ve recently been developing a 2D game for mobile in C# and I’m wondering how to create a shooting mechanic like the one seen in this game.

The ball (just one, not as many as in the video) will shoot and ricochet off walls into enemies. Also the aiming guide line as well. It would be a 2D environment like the game.

Thank you!

I don’t know about mobile development but the basic idea is to get the touch start position - touch end position and then add that as a force to the rigidbody. So at least on pc it would be:

``````    Vector2 mouseStart;
Vector2 mouseEnd;

Rigidbody2D rb;

void Start()
{
rb = GetComponent<Rigidbody2D>();
}

void OnMouseDown()
{
mouseStart = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
}

void OnMouseUp()
{
mouseEnd = new Vector2(Input.mousePosition.x, Input.mousePosition.y);

Vector2 dir = mouseStart - mouseEnd;
}
``````

trajectory is a bit more trickier but i am using a linerenderer and linecasting along the path to detect collisions. Theres one issue i havent solved but the code is:

``````    void UpdateTrajectory(Vector2 initialPosition, Vector2 initialVelocity, Vector2 gravity)
{
int numSteps = 20;
int layerMask = 1 << 8;

float timeDelta = 1.0f / initialVelocity.magnitude;

line.positionCount = numSteps;

Vector2 position = initialPosition;
Vector2 velocity = initialVelocity;

for (int j = 0; j < numSteps; ++j)
{
if (!float.IsNaN(position.x) && !float.IsNaN(position.y))
{
line.SetPosition(j, position);
points[j] = position;
}

position += velocity * timeDelta + 0.5f * gravity * timeDelta * timeDelta;
velocity += gravity * timeDelta;
}

for (int i = 0; i < numSteps - 1; ++i)
{
Debug.DrawLine(points*, points[i + 1]);*
``````

RaycastHit2D hit = Physics2D.Linecast(points*, points[i + 1], layerMask);*
if (hit.collider != null)
{
Debug.Log("HIT: " + hit.point);
line.positionCount = i + 3;
line.SetPosition(i + 2, points*);*
break;
}
}