- Home /
How to get bullet to face the direction it's going?
So i copied a script from a yt channel named Alexander Zotov. He creates a script that shoots bullets from a bullet pool however none of the bullets face the direction their going hence this result:
What do i need to do in order to get bullets to face the direction they're going?
This is the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletFiring : MonoBehaviour
{
[SerializeField]
private int bulletsAmount = 10;
[SerializeField]
private float startAngle = 90f, endAngle = 270f;
private Vector2 bulletMoveDirection;
// Start is called before the first frame update
void Start()
{
InvokeRepeating("Fire", 0f, 2f);
}
// Update is called once per frame
private void Fire()
{
float angleStep = (endAngle - startAngle) / bulletsAmount;
float angle = startAngle;
for (int i = 0; i < bulletsAmount + 1; i++)
{
float bulDirX = transform.position.x + Mathf.Sin((angle * Mathf.PI) / 180f);
float bulDirY = transform.position.y + Mathf.Cos((angle * Mathf.PI) / 180f);
Vector3 bulMoveVector = new Vector3(bulDirX, bulDirY, 0f);
Vector2 bulDir = (bulMoveVector - transform.position).normalized;
GameObject bul = BulletPool.bulletPoolInstanse.GetBullet();
bul.transform.position = transform.position;
bul.transform.rotation = transform.rotation;
bul.SetActive(true);
bul.GetComponent<Bullet>().SetMoveDirection(bulDir);
angle += angleStep;
}
}
}
Answer by logicandchaos · Jun 01, 2021 at 02:43 PM
It's easier to make the bullet move in the direction it's facing, by moving it along transform.forward, then you just rotate in the direction you want it to go and AddForce.
you could get the direction of travel convert it to a rotational value and apply it to the bullet, but that way is more processor intensive and harder.
yeah, i have no clue how to do that, i was expecting that i only needed to add or change a line of code that'd give me the result i want.
You can use a single line of code, which is bullet.rotation = Quaternion.LookRotation(travelDirection);
. This returns a rotation that faces a direction. See Here: Quaternion.LookRotation
Answer by Statement · Jun 02, 2021 at 11:25 AM
Try this, this sets the rotation based on euler angles.
...
bul.transform.position = transform.position;
bul.transform.rotation = Quaternion.Euler(0f, 0f, angle); // Changed this line of code!
bul.SetActive(true);
...
Answer by unity_Q1usDZf64kxuhQ · Jun 02, 2021 at 11:40 PM
yeah i replaced the bit of code with the one you gave me but it seems that the fireballs rotate on each other and only shoot upwards. I think i missed out on a detail is that the sprite shooting the fireballs does not rotate but idk.
Your answer
Follow this Question
Related Questions
Shoot projectile according to rotation 2 Answers
Convert Object Rotation to X, Y values 1 Answer
Camera/Direction Rotation 2 Answers
Shuriken particle trail rotating 1 Answer
Objects Instantiating at wrong position 3 Answers