Issue Firing lazer(bullet) in space game. c#

Hey there,

So I have a simple script which is meant to fire a lazer at the point I have chosen. The issue I’m having is each time I fire a lazer not only is it not moving forward in the direction i want it to, it’s spinning my ship round and round in circles.

This is the Lazer Shooting script:

using UnityEngine;
using System.Collections;

public class WeaponFire : MonoBehaviour {
	public Rigidbody Lazer;
	private float LazerSpeed = 500;
	
	

	void Update () {
		
	if(Input.GetKeyDown(KeyCode.Alpha1)){
			
	Rigidbody FireLazer = Instantiate(Lazer, transform.position,transform.rotation) as Rigidbody;
			
	FireLazer.AddForce(transform.forward * LazerSpeed);
			
		}
	}
}

As you can see it’s very simple. This is my ship movement script, also simple:

using UnityEngine;
using System.Collections;

public class ShipMovement : MonoBehaviour {
	public float Movementspeed;
	public float FTLDrive = 2000;
	
	
	void Update () {
		
        this.transform.position += this.transform.right * Movementspeed * Time.deltaTime * Input.GetAxis("Vertical");
        if(Input.GetKey(KeyCode.A)){
		this.transform.Rotate(Vector3.down, 90 * Time.deltaTime);	
		}
		if(Input.GetKey(KeyCode.D)){
		this.transform.Rotate(Vector3.up, 90 * Time.deltaTime);	
		}
	if(PlayerPrefs.GetInt("UnlockHyperDrive",0)== 2){	
		if(Input.GetKeyDown(KeyCode.LeftShift)){
		Movementspeed = FTLDrive;	
		}
		else if(Input.GetKeyUp(KeyCode.LeftShift)){
		Movementspeed = 100;
		}
		}
		
		
		
	}
}

I have a rigidbody on my ship and have attached one to the lazer prefab. The lazer point where i want the lazer to spawn and fire is also a child of the ship. Can someone help me correct this issue please?

Many thanks in advance.

When two rigidbodies collide with each other, there is a collision resolution algorithm that calculates and applies forces on both objects. This is part of Unity’s physics engine, and that is probably what causes your ship to spin.

There is a solution. There is a method called Physics.IgnoreCollision, which tells unity not to calculate collisions between two specific objects. There are other ways, such as setting the layer collision matrix, or disabling one of the rigidbodies and making one of the colliders a trigger, but Physics.IgnoreCollision is the simplest in my opinion for this case.

if(Input.GetKeyDown(KeyCode.Alpha1)){
    Rigidbody FireLazer = Instantiate(Lazer, transform.position,transform.rotation) as Rigidbody;
    Physics.IgnoreCollision(this.collider, FireLaser.collider);
    FireLazer.AddForce(transform.forward * LazerSpeed);
}

Edit: If your bullet still doesn’t move forward like you expect, share its code so we can help with it as well.