- Home /
2D Top Down Shooting Problem
I'm pretty new to unity so I don't know if the answer is obvious. So I'm working on a top-down shooter where the player is an airplane, and I was trying to make the airplane shoot a laser by making the laser always be to the right of this ship and always turn to where the mouse is and if I left click, a method uses rb.AddForce to make it shoot and then it goes back to where it was in the beginning (to the right of the ship). But when I try it out, the laser does shoot in the direction of my mouse but when it goes back to where it was in the beginning, it starts shaking for like 30 seconds before it goes back to normal.
The script attached to the laser:
using UnityEngine;
public class Shooting : MonoBehaviour {
[SerializeField] Transform shipPos;
[SerializeField] GameObject laserPrefab;
[SerializeField] Rigidbody2D rb;
float angle;
Vector3 laserPos;
Vector2 worldMousePos;
GameObject laser;
[SerializeField] float laserForce;
// Start is called before the first frame update
void Start() {
laserPos.Set(-0.15f, shipPos.position.y, 0.3f);
}
// Update is called once per frame
void Update() {
laserPos.Set(-0.15f, shipPos.position.y, 0.3f);
rb.position = laserPos;
worldMousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 lookDir = worldMousePos - rb.position;
angle = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg - 90f;
rb.rotation = angle;
if (Input.GetButtonDown("Fire1")) {
Shoot();
}
}
void Shoot() {
rb.AddForce(transform.up * laserForce, ForceMode2D.Impulse);
rb.position = laserPos;
}
}
The unity editor (the laser selected):
Answer by Thorgaddon · Feb 25, 2021 at 05:20 PM
Make an Empty Object at laserPrefab spawning point, as a LaserSpawner. Let is spawns laser shots by this:
void Update() {
// some code...
if (Input.GetButtonDown("Fire1"))
{
Instantiate(laserPrefab, LaserSpawner.position, Quaternion.identity)
}
}
and then change Sooting class
public class Shooting : MonoBehaviour { private float laserSpeed;
// Update is called once per frame
void Update()
{
transform.Translate(Vector2.right * laserSpeed * Time.deltaTime);
//+ implement screen border check
}
}
Your answer
Follow this Question
Related Questions
Why isn't my 2d object facing the way it is moving? 0 Answers
Best way to do animate soldier? 1 Answer
Top-down movement in 2D 1 Answer
Random AI patrol movement 3 Answers