- Home /
2D Top Down - Set bullet direction according to turret direction
Hey all,
I know there are some some questions like this, but i've tried all of them without success.
I'm trying to set the bullets direction according to a turret direction in a top down shooter. But I i'm failing in figure out how to get the bullets in the "right" position, here is what i mean:
The bullets should go in the current target's direction, the one the turret is pointing to, but they are being fired from the turret's left.
Here is the code I'm using:
using UnityEngine;
using System.Collections;
public class Turret : Weapon {
[SerializeField]
private Animator anim;
void FixedUpdate() {
Collider2D collider = Physics2D.OverlapCircle(transform.position, 2f, 1 << LayerMask.NameToLayer("Enemy"));
if (collider)
{
Vector3 diff = collider.transform.position - transform.position;
diff.Normalize();
float rot_z = Mathf.Atan2(diff.y, diff.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rot_z - 90);
anim.SetTrigger("Shot");
FireBullet();
}
else {
anim.SetTrigger("Release");
audioSource.Stop();
}
collider = null;
}
protected override void FireBullet()
{
//the position where the bullet will be spawned
var pos = shotPosition.transform.position;
//the turret rotation
var qt = rotationPivot.transform.rotation;
GameObject currentBullet = (GameObject)Instantiate(bulletPrefab, pos, qt);
currentBullet.GetComponent<Bullet>().SetDamage(damage);
Vector3 forceVector = rotationPivot.transform.right;//already tryed: transform.foward, transform.up
currentBullet.GetComponent<Rigidbody2D>().AddForce(forceVector * bulletSpeed * 1.5f, ForceMode2D.Impulse);
}
}
Here is my Hierarchy:
I'm a newbie to Unity and Game development, any help will be very appreciated.
Thanks!
Answer by Jessespike · Jun 14, 2016 at 07:46 PM
Ideally, transform.forward should return a vector of that's in front of the transform. Sometimes the sprite will be rotated, so the front is actually the side. I'm guessing that's the problem here. You can probably adjust the rotation offset with your own variable to compensate. Example:
Vector3 rotationOffset = new Vector3(0f, 90f, 0f);
Vector3 forceVector = transform.forward + rotationOffset;
Hi @jessespike, thanks for your answer, but I had no success trying that. Any other alternative?
Your answer
Follow this Question
Related Questions
Bullet reload problem 3 Answers
Top down radial shooting 1 Answer
Health System Raycast Bullets 2 Answers
Bullets fall 4 Answers
Bullet Hole sprites don't align correctly on walls 2 Answers