Hi, I’m not new to programming but I haven’t done much in Unity. I’m writing a script that’s responsible for shooting at the mouse. I’ve been struggling with it for a few days now and it doesn’t work either when I write it myself or when I follow the tutorial. I have a lot of errors, if their content is needed I’ll send it. Here are two scripts I’m having trouble with:
First script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Schoting : MonoBehaviour
{
[SerializeField] private Rigidbody2D rb;
private Vector3 mousePos = new Vector3(0f, 0f, 0f);
private float speed = 20;
GameObject prefab;
public float czas;
public float czas_max;
public bool canFire;
//public Transform pocisk_poz;
private Camera cam;
//private Vector3 pocisk_poz;
private void Start()
{
cam = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Camera>();
/*inputX = Input.GetAxis("Horizontal");
inputY = Input.GetAxis("Vertical");
pocisk_poz = new Vector3(inputX, inputY, 0);
bool wystrzelono = false;
cam = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Camera>();
Vector3 kierunek;
kierunek.Normalize();
*/
}
private void Update()
{
mousePos = new Vector3(cam.ScreenToWorldPoint(Input.mousePosition));
//Vector3 rotacja = mousePos - transform.position;
//float rotZ = Mathf.Atan2(rotacja.y, rotacja.x) * Mathf.Rad2Deg;
//transform.rotation = transform.rotation * Quaternion.Inverse(Quaternion.Euler(0, 0, rotZ));
if(!canFire)
{
czas += Time.deltaTime;
if(czas > czas_max)
{
canFire = true;
czas = 0;
}
}
if(Input.GetKeyDown(0))
{
canFire = false;
shoot;
}
}
void shoot()
{
GameObject prefab = Instantiate(pocisk, transform.position, Quaternion.identity);
}
}
Second script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Pocisk : MonoBehaviour
{
public Schoting sh;
Vector3 mouse;
void Start()
{
}
void Update()
{
//float rotZ = Mathf.Atan2(rotacja.y, rotacja.x) * Mathf.Rad2Deg;
//transform.rotation = transform.rotation * Quaternion.Inverse(Quaternion.Euler(0, 0, rotZ));
mousePos = new Vector3(cam.ScreenToWorldPoint(Input.mousePosition));
if(Input.GetKeyDown(0))
{
mouse = sh.mousePos;
}
transform.position += mouse;
}
}
Please help me, I will be very grateful.
(Sorry for language mistakes, but I don’t know English very well)