鼠标的按下:Input.GetMouseButtonDown()
鼠标的松开:Input.GetMouseButtonUp()
检测鼠标是否处于按下状态,若是则执行其中的代码:Input.GetMouseButton()
()内可以填0,1,2。
0是指鼠标左键。
1是指鼠标右键。
2是指鼠标中键。
注意:需要在game窗口内点,否则无法生效。
下面的代码,实现了通过点击来控制物体的旋转。比如说,用鼠标在game窗口左击一下,绑定代码的物体就会进行旋转,再左击一下,物体就会停止旋转,再左击一下,物体就会继续旋转……
可以看到,这种逻辑主要是依靠k来实现的,本来我是想用if来判断k的值是不是偶数的,如果是偶数那么就不执行旋转代码,但是用if感觉会拖慢代码的运算速度快,所以直接将k%2用到了求r上,可以看到,如果k%2==0,那么r也会等于0,这相当于是变相的实现了原本需要if才能实现的功能。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class mouse : MonoBehaviour
{
private int k=0;
public float w = 0;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
w = 100;
k++;
}
float r =(k%2)* w * Time.deltaTime;
this.transform.Rotate(0, r, 0, Space.Self);
}
}