- Home /
Ship won't shoot right in SMHUP. Help??
I'm currently working on a SHMUP/bullet hell game. I've started coding the player to shoot a laser. The problem is that every time I test the game, the laser doesn't shoot right. It shoots in the correct direction (just up) if the ship stays still or move up and down. The moment it moves either left or right, the laser curves to whichever side it moved to. Here's my code:
public class playerFire : MonoBehaviour {
public GameObject laserPrefab;
public float fireDelay = 0.05f;
float cooldownTimer = 0;
void Update(){
cooldownTimer -= Time.deltaTime;
if(Input.GetButton("Fire1") && cooldownTimer <= 0){
cooldownTimer = fireDelay;
Instantiate (laserPrefab, transform.position, transform.rotation);
}
}
}
I'd appreciate if someone could help me fix my code. The problem doesn't have anything to do with the fire delay or cooldown. This just helps with fire rate.
Answer by epn2365 · Apr 22, 2018 at 03:24 AM
I found a solution.
public class playerFire : MonoBehaviour {
public GameObject laserPrefab;
public GameObject shipRef;
public float fireDelay = 0.05f;
float cooldownTimer = 0;
void Update(){
cooldownTimer -= Time.deltaTime;
if(Input.GetButton("Fire1") && cooldownTimer <= 0){
cooldownTimer = fireDelay;
GameObject bullet = (GameObject)Instantiate (laserPrefab);
bullet.transform.position = shipRef.transform.position;
}
}
}
Answer by Cherno · Apr 22, 2018 at 12:12 AM
Well, the laser projectile is instantiated so it is rotated the same way as the ship, so if the ship if tilted to the left, so is the projectile. If the laser should always shoot straight up, you would have to change it's rotation. If it's a 2D game where x is the left-right axis and y the up-down axis, you would use:
GameObject projectile = Instantiate (laserPrefab, transform.position, Quaternion.identity);
projectile.transform.eulerAngles = Vector3.up;
Note that transform.forward, transform.rotation etc. is always relative to the local rotation, while Vector3.up, Vector3.right etc. is in global/world space (where forward is always along the positive axis, right is always the positive x axis, etc.).
Thank you for the reply. Unfortunately, this did not solve the issue. I still had the same problem. I even checked to make sure that my ship did not tilt during movement. The moment its position on the x-axis changes to anything above or below zero, the laser curves.
$$anonymous$$ight be a problem with the Physics engine. How are you rotating the ship, and do you apply any force to the projectile when it is instantiated? What happens if you use Vector3.zeri as the eulerAngles of the proejctile.transform?
The ship does not rotate. It only moves left/right up/down. Vector.zero doesn't change anything.
Your answer
Follow this Question
Related Questions
velocity of bullet in rifile rotation 1 Answer
Optimizing Code 1 Answer
How should I handle masses of bullets? 1 Answer
Problem with Shooting Accuracy 0 Answers
Error in shooting script 0 Answers