Search Unity

making my character weapon turn help!!!

Discussion in 'Scripting' started by zizonjuan, May 10, 2019.

  1. zizonjuan

    zizonjuan

    Joined:
    Apr 4, 2019
    Posts:
    21
    a.PNG when I run this my weapon should face the direction of my mouse but it does that for like 1second and it stops
    and it doesn't face the position of my mouse anymore
    what should I do?
     
  2. jvo3dc

    jvo3dc

    Joined:
    Oct 11, 2013
    Posts:
    1,520
  3. zizonjuan

    zizonjuan

    Joined:
    Apr 4, 2019
    Posts:
    21
     
  4. zizonjuan

    zizonjuan

    Joined:
    Apr 4, 2019
    Posts:
    21
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class weapon : MonoBehaviour
    6. {
    7.     public float offset;
    8.     public GameObject projecttile;
    9.     public Transform shotpoint;
    10.     private float timebtwshots;
    11.     public float starttimebtwshots;
    12.     // Start is called before the first frame update
    13.     void Start()
    14.     {
    15.      
    16.     }
    17.  
    18.     // Update is called once per frame
    19.     void Update()
    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.         Debug.Log("moveing");
    25.  
    26.         if (timebtwshots <= 0)
    27.         {
    28.             if (Input.GetMouseButtonDown(0))
    29.             {
    30.                 Instantiate(projecttile, shotpoint.position, transform.rotation);
    31.                 timebtwshots = starttimebtwshots;
    32.             }
    33.  
    34.         }
    35.         else
    36.         {
    37.             timebtwshots -= Time.deltaTime;
    38.         }
    39.      
    40.     }
    41. }
    42.  
    here
     
  5. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,635
    Does it still happen if you remove the offset?
     
  6. zizonjuan

    zizonjuan

    Joined:
    Apr 4, 2019
    Posts:
    21
    yes it still don't work and I just found out that when I move my character It turns properly but when I stay still I wouldn't move
     
  7. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,635
    This line of code:
    Code (CSharp):
    1. transform.rotation = Quaternion.Euler(0f, 0f, rotZ+ offset);
    You are setting the rotation every frame, whether the mouse is moving or not. So when the mouse stops moving, the rotation is going to snap back to (0,0,offset) regardless of where it was.
     
  8. zizonjuan

    zizonjuan

    Joined:
    Apr 4, 2019
    Posts:
    21
    then what should I do?