- Home /
I shoot a projectile, but its rotation is wrong (c#)
Hello again.
I made a few scripts in my flight sim so my aircraft shoots projectiles, but i can't figure out a way to make it instantiate in the angle that i want.
Projectile Script:
using UnityEngine;
using System.Collections;
public class Projectile : MonoBehaviour {
public float speed = 60.0f;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
transform.Translate(new Vector3(0.0f, 0.0f ,speed*Time.deltaTime ));
}
}
Script that spawns the Projectile:
using UnityEngine;
using System.Collections;
public class shipshoot : MonoBehaviour {
public GameObject playerProjectile;
public Transform Source;
public float TimeBetweenShots = 0.2f;
private float _NextSHot = 0.0f;
// Use this for initialization
void Start () {
Source = transform;
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButton(0) && Time.time > _NextSHot)
{
_NextSHot = Time.time + TimeBetweenShots;
Instantiate(playerProjectile, Source.position, Source.rotation);
}
}
}
The result of everything above is this:
But i want the projectile to come out like this:
Any ideas?
Place the object in the scene. Place how you would want it to be spawned then from there make it a prefab and then instantiate the prefab. It should work. ALso double check rotation is Quaternion.Identity.
Your idea didn't work. The projectile still spawns as a regular capsule would.
Also when i use Quaternion.Identity, the projectile spawns at the RIGHT side of the ship ins$$anonymous$$d of the front.
Answer by robertbu · Jul 28, 2013 at 01:45 AM
The easiest way to fix this problem is to create an empty game object, make the capsule a child of the empty game object and then apply a rotation to the visible object. Scripts go on the empty game object.
You can also calculate the rotation. You said 'capsule' so I'm assuming you want the 'y' of the capsule to point forward. And I'm assuming you are firing out the front (side facing positive 'z' when the ship has no rotaiton). Put these three lines in place of line 24:
GameObject go = Instantiate(playerProjectile, Source.position, Quaternion.identity) as GameObject;
Quaternion q = Quaternion.FromToRotation(Vector3.up, transform.forward);
go.transform.rotation = q * go.transform.rotation;
I get error CS0266 : Cannot implicitly convert type UnityEngine.Object' to
UnityEngine.GameObject'. An explicit conversion exists (are you missing a cast?)
your first suggestion didn't help either. Ins$$anonymous$$d of getting the projectile correctly, i got nothing
I fixed the script above by adding 'as GameObject'. For the first one to work, you need the position of the child (visible) object to be at (0,0,0) relative to the parent. You probably have an offset.
@robertbu Hey, robert, is there any simple intuition behind multiplying the Quaternions to get the rotation I want. It works, I just don't get why.