- Home /
How to shoot in the same direction my character is facing?
Hi,
I'm new to Unity and trying to program a script for my TopDown-Shooter I'm working on. I have some issues concerning the direction the bullet is spawning and flying. I made a Prefab of my Bullet, named it "Bolt" and added the following Script:
using UnityEngine;
using System.Collections;
public class Mover : MonoBehaviour {
public float speed;
void Start ()
{
GetComponent<Rigidbody2D> ().velocity = transform.forward * speed;
}
}
And here's the script, which handles the character movement and shooting part:
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour {
public float speed1;
public GameObject shot;
public Transform shotSpawn;
public float fireRate;
private float nextFire;
void Update () {
if (Input.GetButton ("Fire1") && Time.time > nextFire) {
nextFire = Time.time + fireRate;
Instantiate (shot, shotSpawn.transform.position, shotSpawn.transform.rotation);
}
if (Input.GetKey (KeyCode.D)) {
transform.Translate (Vector2.right * speed1);
}
if (Input.GetKey (KeyCode.A)) {
transform.Translate (-Vector2.right * speed1);
}
if (Input.GetKey (KeyCode.W)) {
transform.Translate (Vector2.up * speed1);
}
if (Input.GetKey (KeyCode.S)) {
transform.Translate (-Vector2.up * speed1);
}
}
}
There are 2 problems with this script:
Pressing the Firebutton results in "laying" shots, they're not flying, they only spawn and remain at the same position.
The other problem is, that the shots don't spawn in the direction my character is facing.
What am I doing wrong?
Answer by applemaniac · Jun 08, 2015 at 08:48 AM
You can use Vector3.forward to know what direction your character is facing, and use it in something like yourBullet.GetComponent().AddForce(transform.forward * power)
There is a script attached to the Prefab of my bullet, which contains a similar code to what you suggested:
void Start (){
GetComponent<Rigidbody2D>().velocity = transform.forward * speed1;
In the Player$$anonymous$$ovement-Script I added something like shotSpawn.transform.rotation = Quaternion.Euler(0,0,-180);
every time a certain $$anonymous$$ey is pressed. The shotSpawn seems to rotate, I can see the Z-valuable change in the Inspector of the shotSpawn everytime I press a certain key, but the shot keeps flying down.
Any suggestions?
And Thanks in advance!
Check the usual problems : colliders, frozen degrees, and try with AddForce()
Answer by MicDaRoc · Jun 11, 2015 at 08:53 AM
Ok, i solved it. I set the Gravityscale to 0 and added this line of code to the moverscript:
GetComponent().AddForce(-transform.up * speed1);
Can you post your full code, i just cant seem to get $$anonymous$$e to work