Search Unity

my bullet doesn't work properly

Discussion in 'Scripting' started by zizonjuan, Jun 1, 2019.

  1. zizonjuan

    zizonjuan

    Joined:
    Apr 4, 2019
    Posts:
    21
    I'm trying to fire a bullet toward the mouse but if I fire then it goes to the wrong direction what should I do?
    and the offset I set is 90
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class weapon : MonoBehaviour
    6. {
    7.     public GameObject projectile;
    8.     public Transform shotposition;
    9.     private float Timebtwshots;
    10.     public float starttime;
    11.     public float offset;
    12.     void Start()
    13.     {
    14.        
    15.     }
    16.  
    17.     // Update is called once per frame
    18.     void Update()
    19.     {
    20.  
    21.         Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
    22.         float rotz = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
    23.         transform.rotation = Quaternion.Euler(0f, 0f, rotz + offset);
    24.         if (Timebtwshots <= 0)
    25.         {
    26.             if (Input.GetMouseButtonDown(0))
    27.             {
    28.                 Instantiate(projectile, shotposition.position, transform.rotation);
    29.                 Timebtwshots = starttime;
    30.             }
    31.         }else
    32.         {
    33.             Timebtwshots -= Time.deltaTime;
    34.         }
    35.     }
    36. }
    37.  
    this is the code for my weapon
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class projectile : MonoBehaviour
    6. {
    7.     public float speed;
    8.     public float lifetime;
    9.    
    10.     void Start()
    11.     {
    12.         Invoke("DestroyProjectile",lifetime);
    13.     }
    14.  
    15.     // Update is called once per frame
    16.     void Update()
    17.     {
    18.         transform.Translate(transform.up* speed *Time.deltaTime);
    19.     }
    20.     void DestroyProjectile()
    21.     {
    22.         Destroy(gameObject);
    23.     }
    24. }
    25.  
    and this is the code for my bullet
     
  2. zizonjuan

    zizonjuan

    Joined:
    Apr 4, 2019
    Posts:
    21
    sorry I forgot to change transform.Translate(transform.up* speed *Time.deltaTime);
    in to transform.Translate(Vertor2.up* speed *Time.deltaTime);