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.
https://www.youtube.com/watch?v=veQQi7I5CzM
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!
Answer by Laktoosi · Jul 19, 2018 at 07:32 AM
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;
rb.AddForce(dir * 5);
}
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;
layerMask = ~layerMask;
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[i], points[i + 1]);
RaycastHit2D hit = Physics2D.Linecast(points[i], points[i + 1], layerMask);
if (hit.collider != null)
{
Debug.Log("HIT: " + hit.point);
line.positionCount = i + 3;
line.SetPosition(i + 2, points[i]);
break;
}
}
Hi! Thank you for the codes, the shooting works fine! Just asking what the variables for 'line' and 'points' are in the trajectory code.
Ah yeah those are just Linerenderer component and the points are an array for the linecast and linerenderer to follow
LineRenderer line;
Vector2[] points = new Vector2[20];
void Start()
{
line = GetComponent<LineRenderer>();
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612171040im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Is It Bad to be Tired of my Own Mobile Game? 1 Answer
Shooting bullets up (y axis) 0 Answers
Unity 2d simple c# shooting script 1 Answer
No overload for method 'fireBullet' takes 0 arguments 1 Answer
Unity 2D bullet bounce 0 Answers