Search Unity

How can ı change mouse click to Key in my script ?

Discussion in 'Editor & General Support' started by Lupinder, Jan 6, 2021.

  1. Lupinder

    Lupinder

    Joined:
    Oct 6, 2018
    Posts:
    85
    I dont wanna activate code with mouse clicks. I want to press "W" for activate code. I am using proinput and things little bit complicated at now. How can ı change "rightButton" to "w" for keyboard ? First script is proinput script. Other is my original script which i want to change mouse click to "w". Thanks for help...

    Code (CSharp):
    1. using System.Collections.Generic;
    2. using System.Linq;
    3. using UnityEngine;
    4. using UnityEngine.InputSystem;
    5.  
    6. namespace ProInput.Scripts {
    7.     /// <summary>
    8.     /// Main class of ProInput
    9.     /// Outside classes should mainly invoke this class
    10.     /// </summary>
    11.     public class ProInput : MonoBehaviour {
    12.         private static ProInput _proInput;
    13.         private static bool _initialized;
    14.  
    15.         private Dictionary<string, InputObject> _enabledBindings;
    16.  
    17.         /// <summary>
    18.         /// Initializes ProInput
    19.         /// If already initialized, destroys object
    20.         /// Doesn't destroy on load
    21.         /// </summary>
    22.         private void Awake() {
    23.             // Checks if is initialized
    24.             if (_initialized) {
    25.                 Destroy(gameObject);
    26.                 return;
    27.             }
    28.  
    29.             // Initializes ProInput
    30.             _initialized = true;
    31.             _proInput = this;
    32.             DontDestroyOnLoad(gameObject);
    33.             _enabledBindings = new Dictionary<string, InputObject>();
    34.         }
    35.  
    36.         /// <summary>
    37.         /// Function called on update loop
    38.         /// </summary>
    39.         private void FixedUpdate() {
    40.             var current = Keyboard.current;
    41.             GetInputObjects().ForEach(o => o.Update(current));
    42.         }
    43.        
    44.         /// <summary>
    45.         /// Function called on application exit
    46.         /// </summary>
    47.         private void OnApplicationQuit() {
    48.             GetInputObjects().ForEach(o => o.Save());
    49.         }
    50.  
    51.         /// <summary>
    52.         /// Converts dictionary to list
    53.         /// </summary>
    54.         /// <returns>InputObject list</returns>
    55.         private List<InputObject> GetInputObjects() {
    56.             return _enabledBindings.Values.ToList();
    57.         }
    58.  
    59.         /// <summary>
    60.         /// Add inputObject to bindings
    61.         /// </summary>
    62.         /// <param name="inputObject">New input</param>
    63.         public static void RegisterInput(InputObject inputObject) {
    64.             _proInput._enabledBindings.Add(inputObject.Name, inputObject);
    65.         }
    66.     }
    67. }
    68.  
    Code (CSharp):
    1. using System;
    2. using System.Diagnostics;
    3. using Player;
    4. using ProInput.Scripts;
    5. using Rope;
    6. using Unity.Collections;
    7. using UnityEngine;
    8.  
    9. namespace Carriable.Carriables
    10. {
    11.     public class Shift : MonoBehaviour
    12.     {
    13.      
    14.      
    15.         private const float IDLE_FOV = 86f;
    16.         private const float WALK_FOV = 85f;
    17.         private const float SWİN_FOV = 109f;
    18.         private const float RUN_FOV = 88f;
    19.         private const float CROUCH_FOV = 78f;
    20.         private const float NORMAL_FOV = 111f;
    21.         private const float HOOKSHOT_FOV = 114f;
    22.         public AudioClip _soundd;    // this lets you drag in an audio file in the inspector
    23.         public AudioSource audioo;
    24.         private CameraFov cameraFov;
    25.  
    26.  
    27.         private float timer = 0f;
    28.  
    29.         public GameObject otherObject;
    30.         Animator otherAnimator;
    31.         void Start()
    32.         {
    33.  
    34.             otherAnimator = otherObject.GetComponent<Animator>();
    35.             audioo = audioo; //oadds an AudioSource to the game object this script is attached to
    36.             audioo.playOnAwake = false;
    37.             audioo.clip = _soundd;
    38.             audioo.Stop();
    39.             cameraFov = playerCamera.GetComponent<CameraFov>();
    40.             speedLinesParticleSystem = transform.Find("Camera").Find("SpeedLinesParticleSystem").GetComponent<ParticleSystem>();
    41.  
    42.  
    43.  
    44.  
    45.  
    46.         }
    47.  
    48.  
    49.         [Header("Grappling")]
    50.         public GrapplingRope grapplingRope;
    51.         public PlayerController player;
    52.         public Transform grappleTip;
    53.         public Transform grappleHolder;
    54.         public int whatToGrapple;
    55.         public float maxDistance;
    56.         public float minDistance;
    57.         public float rotationSmooth;
    58.         public bool Swin;
    59.         public bool Swinnn;
    60.         public ParticleSystem speedLinesParticleSystem;
    61.         public Camera playerCamera;
    62.  
    63.  
    64.  
    65.  
    66.         [Header("Raycasts")]
    67.         public float raycastRadius;
    68.         public int raycastCount;
    69.  
    70.         [Header("Physics")]
    71.         public float pullForce;
    72.         public float pushForce;
    73.         public float yMultiplier;
    74.         public float minPhysicsDistance;
    75.         public float maxPhysicsDistance;
    76.  
    77.         private Vector3 _hit;
    78.  
    79.         private void Update()
    80.         {
    81.             timer += Time.deltaTime;
    82.         }
    83.  
    84.         private void FixedUpdate()
    85.         {
    86.  
    87.  
    88.             if (ProMouse.RightButton.IsPressed && grapplingRope.Grappling)
    89.             {
    90.  
    91.  
    92.                 grappleHolder.rotation = Quaternion.Lerp(grappleHolder.rotation, Quaternion.LookRotation(-(grappleHolder.position - _hit)), rotationSmooth * Time.fixedDeltaTime);
    93.  
    94.  
    95.                 var distance = Vector3.Distance(player.transform.position, _hit);
    96.                 if (!(distance >= minPhysicsDistance) || !(distance <= maxPhysicsDistance)) return;
    97.  
    98.                 if (timer >= 0.0063f)
    99.                 {
    100.                     timer = 0f;
    101.  
    102.                     player.playerRigidBody.velocity += pullForce * Time.fixedDeltaTime * yMultiplier * Mathf.Abs(_hit.y - player.transform.position.y) * (_hit - player.transform.position).normalized;
    103.                     player.playerRigidBody.velocity += pushForce * Time.fixedDeltaTime * player.transform.forward;
    104.  
    105.                 }
    106.             }
    107.             else
    108.             {
    109.                 grappleHolder.localRotation = Quaternion.Lerp(grappleHolder.localRotation, Quaternion.Euler(0, 0, 0), rotationSmooth * Time.fixedDeltaTime);
    110.             }
    111.         }
    112.  
    113.  
    114.         private void LateUpdate()
    115.         {
    116.          
    117.             if (this.otherAnimator.GetCurrentAnimatorStateInfo(0).IsName("Main Release"))
    118.             {
    119.                 cameraFov.SetCameraFov(Main_FOV);
    120.             }
    121.  
    122.  
    123.             if (ProMouse.RightButton.IsDown && RaycastAll(out var hitInfo))
    124.             {
    125.  
    126.                 if (Input.GetButtonDown("left alt"))
    127.                 {
    128.                     audioo.Play();
    129.  
    130.                 }
    131.                 cameraFov.SetCameraFov(HOOKSHOT_FOV);
    132.  
    133.  
    134.  
    135.                 speedLinesParticleSystem.Play();
    136.                 otherAnimator.SetBool("Swinnn", true);
    137.  
    138.  
    139.  
    140.  
    141.                 grapplingRope.Grapple(grappleTip.position, hitInfo.point);
    142.                 _hit = hitInfo.point;
    143.  
    144.  
    145.  
    146.  
    147.  
    148.  
    149.  
    150.             }
    151.  
    152.  
    153.  
    154.             if (ProMouse.RightButton.IsUp)
    155.             {
    156.                 cameraFov.SetCameraFov(NORMAL_FOV);
    157.                 speedLinesParticleSystem.Stop();
    158.                 otherAnimator.SetBool("Swinnn", false);
    159.  
    160.  
    161.                 grapplingRope.UnGrapple();
    162.  
    163.             }
    164.  
    165.  
    166.  
    167.  
    168.             if (ProMouse.RightButton.IsPressed && grapplingRope.Grappling)
    169.             {
    170.  
    171.  
    172.  
    173.                 otherAnimator.SetBool("Swinnn", true);
    174.  
    175.                 grapplingRope.UpdateStart(grappleTip.position);
    176.  
    177.  
    178.  
    179.  
    180.             }
    181.             grapplingRope.UpdateGrapple();
    182.  
    183.         }
    184.  
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,742
    Check out the
    Input
    class, probably the
    GetKey()
    or
    GetKeyDown()
    methods.
     
  3. Lupinder

    Lupinder

    Joined:
    Oct 6, 2018
    Posts:
    85
    This is input script. I am little bit confused about what i will change. Like i said i just wanna use "w" key instead mouse right click.
    Code (CSharp):
    1. public class InputObject {
    2.         // Default folder for bindings
    3.         private const string BindingsFolder = "Bindings";
    4.        
    5.         // Handle used to save binding
    6.         private readonly SaveHandle<BKey> _saveHandle;
    7.         private readonly string _name;
    8.         private Key _binding;
    9.  
    10.         private bool _isPressed;
    11.         private bool _isDown;
    12.         private bool _isUp;
    13.  
    14.         /// <summary>
    15.         /// Constructor for InputObject
    16.         /// </summary>
    17.         /// <param name="name">Name of the input</param>
    18.         /// <param name="defaultValue">Default binding</param>
    19.         public InputObject(string name, Key defaultValue) {
    20.             var directory = $"{Application.persistentDataPath}/{BindingsFolder}";
    21.             if (!System.IO.Directory.Exists(directory))
    22.                 System.IO.Directory.CreateDirectory(directory);
    23.            
    24.             _name = name;
    25.             _saveHandle = new SaveHandle<BKey>($"{BindingsFolder}/{name}_bind");
    26.  
    27.             var loadedData = _saveHandle.LoadData();
    28.             _binding = loadedData ?? defaultValue;
    29.             ProInput.RegisterInput(this);
    30.         }
    31.  
    32.         /// <summary>
    33.         /// Update input state
    34.         /// </summary>
    35.         /// <param name="current">Active keyboard</param>
    36.         public void Update(Keyboard current) {
    37.             var input = current.allKeys.First(control => control.keyCode == _binding);
    38.             var pressed = input.isPressed;
    39.             _isDown = !_isPressed && pressed;
    40.             _isUp = _isPressed && !pressed;
    41.             _isPressed = pressed;
    42.         }
    43.  
    44.         /// <summary>
    45.         /// Function called on application exit or saving
    46.         /// </summary>
    47.         public void Save() {
    48.             _saveHandle.SaveData(_binding);
    49.         }
    50.  
    51.         /// <summary>
    52.         /// Bind input to new key
    53.         /// </summary>
    54.         public void Bind(Key key) {
    55.             _binding = key;
    56.             Save();
    57.         }
    58.  
    59.         public string Name => _name;
    60.         public bool IsPressed => _isPressed;
    61.         public bool IsDown => _isDown;
    62.         public bool IsUp => _isUp;
    63.     }
    64. }
    65.  
    66.  
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,742
    Steps to success:

    1. identify in your code where you accept the click
    2. insert an additional check of the methods I suggested above to also accept the keypress
    3. act upon the click in precisely the same way regardless of how it arrived

    Code (csharp):
    1. // pseudocode, will NOT compile:
    2. bool clicked = false;
    3. if (mousehit) clicked = true;
    4. if (keyhit) clicked = true;
    5. if (clicked)
    6. {
    7.   DoTheThingIWant();
    8. }
     
  5. Lupinder

    Lupinder

    Joined:
    Oct 6, 2018
    Posts:
    85
    I think i am so close to solve. My question is how can ı activate script with double mouse click at same time. I want to press right and left at same time and activate code. Can you help me about that ?
    Code (CSharp):
    1.  private void FixeddUpdate()
    2.         {
    3.  
    4.            
    5.             if (ProMouse.RightButton.IsPressed && ProMouse.LeftButton.IsPressed && grapplingRope.Grappling )
    6.             {
    7.  
    8.  
    9.                 grappleHolder.rotation = Quaternion.Lerp(grappleHolder.rotation, Quaternion.LookRotation(-(grappleHolder.position - _hit)), rotationSmooth * Time.fixedDeltaTime);
    10.  
    11.  
    12.                 var distance = Vector3.Distance(player.transform.position, _hit);
    13.                 if (!(distance >= minPhysicsDistance) || !(distance <= maxPhysicsDistance)) return;
    14.  
    15.                 if (timer >= 0.0063f)
    16.                 {
    17.                     timer = 0f;
    18.  
    19.                     player.playerRigidBody.velocity += pullForce * Time.fixedDeltaTime * yMultiplier * Mathf.Abs(_hit.y - player.transform.position.y) * (_hit - player.transform.position).normalized;
    20.                     player.playerRigidBody.velocity += pushForce * Time.fixedDeltaTime * player.transform.forward;
    21.  
    22.  
    23.                 }
    24.             }
    25.             else
    26.             {
    27.                 grappleHolder.localRotation = Quaternion.Lerp(grappleHolder.localRotation, Quaternion.Euler(0, 0, 0), rotationSmooth * Time.fixedDeltaTime);
    28.             }
    29.         }
    30.  
    31.  
    32.         private void LateUpdate()
    33.         {
    34.          
    35.             if (this.otherAnimator.GetCurrentAnimatorStateInfo(0).IsName("Scene 0"))
    36.             {
    37.                 cameraFov.SetCameraFov(Main_FOV);
    38.             }
    39.  
    40.  
    41.             if (ProMouse.RightButton.IsDown && ProMouse.LeftButton.IsDown && RaycastAll(out var hitInfo))
    42.             {
    43.  
    44.                 if (Input.GetButtonDown("Fire2"))
    45.                 {
    46.                     audioo.Play();
    47.  
    48.                 }
    49.                 cameraFov.SetCameraFov(HOOKSHOT_FOV);
    50.  
    51.  
    52.  
    53.                 speedLinesParticleSystem.Play();
    54.                 otherAnimator.SetBool("Swinnn", true);
    55.  
    56.  
    57.  
    58.  
    59.                 grapplingRope.Grapple(grappleTip.position, hitInfo.point);
    60.                 _hit = hitInfo.point;
    61.  
    62.  
    63.  
    64.             }
    65.  
    66.  
    67.             if (ProMouse.RightButton.IsUp && ProMouse.LeftButton.IsUp)
    68.             {
    69.                 cameraFov.SetCameraFov(NORMAL_FOV);
    70.                 speedLinesParticleSystem.Stop();
    71.                 otherAnimator.SetBool("Swinnn", false);
    72.  
    73.  
    74.                 grapplingRope.UnGrapple();
    75.  
    76.             }
    77.  
    78.  
    79.  
    80.  
    81.             if (ProMouse.RightButton.IsPressed && ProMouse.LeftButton.IsPressed && grapplingRope.Grappling)
    82.             {
    83.  
    84.  
    85.  
    86.                 otherAnimator.SetBool("Swinnn", true);
    87.  
    88.                 grapplingRope.UpdateStart(grappleTip.position);
    89.  
    90.  
    91.             }
    92.             grapplingRope.UpdateGrapple();
    93.  
    94.         }
     
  6. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,742
    Double click can be done by making a
    float
    timer that you you count down every frame by
    Time.deltaTime;


    When you click, check if that value is greater than zero. If so, consider it a double-click.

    If not, then consider it a single-click and set that timer to the doubleclick interval.