Trouble with controlling the direction of projectiles with C# code
I am making a group project for a game design class I am taking, and I am having trouble with controlling the direction the projectile that is launched from the character's gun goes. Here is my code, tell me if you need any more info to help.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Weapon : MonoBehaviour
{
public float offset;
public GameObject self;
public GameObject projectile;
public Transform shotPoint;
private float timeBtwShots;
public float startTimeBtwShots;
private void Update()
{
Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotZ + offset);
if(timeBtwShots <= 0)
{
if(Input.GetMouseButtonDown(0))
{
Instantiate(projectile, shotPoint.position, self.transform.rotation);
timeBtwShots = startTimeBtwShots;
}
} else
{
timeBtwShots -= Time.deltaTime;
}
}
}
Basically, what is going wrong, is if the gun is pointing up, the projectile should go up. Right, and right. Left, and left, and you get the idea. What is happening, though, is if the gun is up, the projectile goes to the left. If the gun is right, it goes up. If the gun is down, it goes right. If the gun is left, it goes down.
Thank you for any help!
Answer by DrChicken24 · Dec 16, 2019 at 11:38 PM
@jetpackdan Concerning your previous reply (I don't know why it isn't showing up on this thread); When I try to use a Vector3, I get the error of trying to mix a Quaternion and a Vector3, which apparently isn't allowed. I would change self.transform.rotation
to self.transform.rotation.x
, but i then get the error of mixing a Quaternion and a Vector3. Thanks for your reply.