简体   繁体   中英

Problems with GetMouseButtonDown C#

public class PlayerController : MonoBehaviour
{
    public float moveSpeed;
    private Rigidbody myRigidBody;

    private Vector3 moveInput;
    private Vector3 moveVelocity;

    private Camera mainCamera;
    public GunController theGun;
    // Start is called before the first frame update
    void Start()
    {
        myRigidBody = GetComponent<Rigidbody>();
        mainCamera = FindObjectOfType<Camera>();
    }

    // Update is called once per frame
    void Update()
    {
        moveInput = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical"));
        moveVelocity = moveInput * moveSpeed;

        Ray cameraRay = mainCamera.ScreenPointToRay(Input.mousePosition);
        Plane groundPlane = new Plane(Vector3.up, Vector3.zero);
        float rayLength;

        if(groundPlane.Raycast(cameraRay,out rayLength))
        {
            Vector3 pointToLook = cameraRay.GetPoint(rayLength);
            Debug.DrawLine(cameraRay.origin, pointToLook, Color.blue);

            transform.LookAt(new Vector3(pointToLook.x, transform.position.y, pointToLook.z));
        }

        if(Input.GetMouseButtonDown(0))
            print ("The Gun should have fired");
        Debug.Log("Pressed Left Mouse Button.");
            theGun.isFiring = true;

        if (Input.GetMouseButtonDown(0))
            print("The gun should have stopped firing");
            theGun.isFiring = false;
    }
    void FixedUpdate()
    {
        myRigidBody.velocity = moveVelocity;
    }
}

I reckon my problem starts with the if,if statement. The console seems to register the left mouse button as down all the time. and without the debug statement, if i press down, the print text pops up but imediatly goes to the next print even though i never unclicked. With or without the debug or print code, the intended effect never happens. Sorry if formatted wrong, very new to this.

Console of the debug

C# is not like Python... C# doesn't use code blocks by indenting code lines. In c# you'll need to open a block with an { and close it with an } .

So this part will not work like you might think:

if(Input.GetMouseButtonDown(0))
    print ("The Gun should have fired");
    Debug.Log("Pressed Left Mouse Button.");
    theGun.isFiring = true;

// forgot to negate?!
if (Input.GetMouseButtonDown(0))
    print("The gun should have stopped firing");
    theGun.isFiring = false;

Try

if (Input.GetMouseButtonDown(0) && !theGun.isFiring) {
    print ("The Gun should have fired");
    Debug.Log("Pressed Left Mouse Button.");
    theGun.isFiring = true;
} else if (theGun.isFiring) {
    print("The gun should have stopped firing");
    theGun.isFiring = false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM