- Home /
C# Simple turret script problem
Hello!
I have the simplest Turret code which doesn't work. It fires projectiles in Z direction (?!) When player is at the positive x positin of the turret the turret shoots upwards in Z, otherwise downwards. It is always facing the player however. What is wrong?
I attached this code to a simple cube. And the target is a moving player.
using UnityEngine;
using System.Collections;
public class TurretScript : MonoBehaviour {
public GameObject projectile;
public Transform target;
void Start(){
RepeatShooting();
}
void Update(){
transform.rotation = Quaternion.LookRotation (target.position - transform.position);
}
// Shoot and repeat
void RepeatShooting () {
InvokeRepeating ("LaunchProjectile", 2, 0.3f);
}
public void LaunchProjectile(){
//Vector3 projectileStart = new Vector3(
Instantiate (projectile, transform.position, transform.rotation);
}
}
This depends on your projectile. You should hold it in a variable like GameObject projectile = Instantiate... and then Quaterniate it according to player position. Your prefab will always act same.
I have tried that. $$anonymous$$y additional code:
GameObject newProjectile = (GameObject) Instantiate (projectile, transform.position, transform.rotation); newProjectile.transform.rotation = Quaternion.LookRotation (target.position - transform.position);
This give me same results as before.
When I use
Transform.Rotate(Vector3.forward);
as rotation ins$$anonymous$$d, I get a nice spray of projectiles just in the direction of the turret. So I suppose, the Quaternion.LookRotation is messing it up?
I spot no problems in this code (assu$$anonymous$$g that 'target' is initialized correctly). That means the problem is most likely in the code that moves the projectile or you have some sort of collision between the projectile and some collider. Nothing here move the projectile.
Answer by Calum-McManus · Oct 03, 2013 at 04:05 PM
Try making a spawn at the end of the barrel of the turret and using something like this:
Instantiate(Projectile, Spawn.transform.position, Spawn.transform.rotation);
Also use something like this:
Vector3 vSpeedDelta = transform.forward * (Time.deltaTime * ProjectileSpeed);
transform.position += (vSpeedDelta);
Put this in the update of a projectile script and attach that new script to the projectile itself. This should always fire straight assuming the projectile spawn has its forward axis points forward of the barrel.
Trank you all for helping me. The projectile was the problem as you mentioned. It was set to Vector3.right, silly me!
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
Simple question about targetting 0 Answers
Rotating Tank Turret with correct angle 3 Answers