Hi guys, please help.
Really simple thing, but don’t understand how Unity behaves.
I have object which represent Cannon, with has two child objects: Launcher is used for set up initial position of projectile and Target where to shoot.
And there is prefab Projectile.
All I want to do is just to shoot straight through turret wherever I rotate the Cannon.
public class Cannon : MonoBehaviour
{
[SerializeField]
private GameObject ammoPrefab;
[SerializeField]
private float rotationSpeed = 5;
[SerializeField]
private Transform launcher;
[SerializeField]
private Transform target;
private MoveState state = MoveState.Idle;
private void Update()
{
if (Input.GetKeyDown(KeyCode.A))
{
state = MoveState.Left;
}
else if (Input.GetKeyDown(KeyCode.D))
{
state = MoveState.Right;
}
if (Input.GetKeyDown(KeyCode.W))
{
state = MoveState.Up;
}
else if (Input.GetKeyDown(KeyCode.S))
{
state = MoveState.Down;
}
if (Input.GetKeyUp(KeyCode.A) || Input.GetKeyUp(KeyCode.D)
|| Input.GetKeyUp(KeyCode.W) || Input.GetKeyUp(KeyCode.S))
{
state = MoveState.Idle;
}
if (Input.GetMouseButtonDown(0) || Input.GetKeyDown(KeyCode.L))
{
Fire();
}
}
private void FixedUpdate()
{
if (state != MoveState.Idle)
{
SetPosition();
}
}
private void SetPosition()
{
Vector3 rotation = transform.eulerAngles;
switch (state)
{
case MoveState.Left:
if (rotation.y > 170)
{
rotation.y -= rotationSpeed * Time.fixedDeltaTime;
}
break;
case MoveState.Right:
if (rotation.y < 190)
{
rotation.y += rotationSpeed * Time.fixedDeltaTime;
}
break;
case MoveState.Up:
if (rotation.x < 10)
{
rotation.x += rotationSpeed * Time.fixedDeltaTime;
}
break;
case MoveState.Down:
if (rotation.x > 0)
{
rotation.x -= rotationSpeed * Time.fixedDeltaTime;
// reset if goes below 0 degree
if (rotation.x > 10)
{
rotation.x = 0.0f;
}
}
break;
}
transform.eulerAngles = rotation;
}
private void Fire()
{
GameObject ammo = Instantiate(ammoPrefab);
ammo.transform.position = launcher.position;
Projectile ammoScript = ammo.GetComponent<Projectile>();
Debug.DrawLine(launcher.position, target.position, Color.red, 5.0f);
StartCoroutine(ammoScript.TravelTo(target.position));
}
}
public class Projectile : MonoBehaviour
{
[SerializeField]
private float duration = 2.5f;
public IEnumerator TravelTo(Vector3 endPosition)
{
float percentComplete = 0.0f;
while (percentComplete < 1.0f)
{
transform.position = Vector3.Lerp(transform.position, endPosition, percentComplete);
percentComplete += Time.deltaTime / duration;
yield return null;
}
Destroy(gameObject, 0.1f);
}
}
When I rotate the Cannon child objects also rotate, but when shooting the projectile start from different position depending on Cannon rotation.
Shooting on initial position of Cannon.
It’s good.
But after rotation
It’s very bad.