Chadderbox
Chadderbox

Reputation: 65

My addforce is not working where it should

My grapple hook works on the premise that you shoot, it makes an anchor point, and then when you right click, it wheels you towards the anchor point, but this does not work and I do not know why. I would love some help.

I have tried replacing button with buttondown and other buttons, but not mssed with the raycast.

public class PointRotateHook : MonoBehaviour
{
    public Camera cam;
    public Vector3 rayPoint;
    public Rigidbody player;
    public Vector3 force;
    public float range = 30f;
    public Vector3 anchorCast;

    public Vector3 aforce;



    // Update is called once per frame
    void Update()
    {
        if (Input.GetButtonDown("Fire1"))
        {
            RaycastHit anchor;
            if(Physics.Raycast(cam.transform.position, cam.transform.forward, out anchor, range))
            {
               anchorCast = anchor.point;
               aforce = (anchor.point - player.position);
               if (Input.GetButton("Fire2"))
               {
                   player.AddForce((aforce.x * 4), (aforce.y / 4), (aforce.z * 4), ForceMode.VelocityChange);
               }

            }
        }
    }
}

I expect my character to move when right click is pressed, but they stay still and position does not change in the inspector.

Upvotes: 0

Views: 41

Answers (1)

derHugo
derHugo

Reputation: 90580

The first

Input.GetButtonDown("Fire1")

is true only for one frame in which the button was pressed.

Due to your description I assume you are not already pressing Fire2 but what you want is press Fire1 then additionally press Fire2 so it should be exactly the other way round:

if(Input.GetButton("Fire1")
{
    ... // Continuously make the Raycast

    // This still only works if "Fire1" is still pressed
    if(Input.GetButtonDown("Fire2"))
}

This still only works if both buttons will be pressed together meaning "Fire1" stays pressed and "Fire2" is pressed additionally.


If I understand correctly you rather wanted it with two separate button clicks you should rather do e.g.

private bool isHit;

private void Update()
{
    // Handle first button click
    if (Input.GetButtonDown("Fire1"))
    {
        if(Physics.Raycast(cam.transform.position, cam.transform.forward, out var anchor, range))
        {
            isHit = true;
            anchorCast = anchor.point;
            aforce = (anchor.point - player.position);
        }
        else
        {
            isHit = false;
        }
    }

    //TODO: Maybe reset isHit after time or on the next Fire1 press?

    // Handle Fire2 sperated only if isHit was set to true before
    if (isHit && Input.GetButton("Fire2"))
    {
        player.AddForce((aforce.x * 4), (aforce.y / 4), (aforce.z * 4), ForceMode.VelocityChange);
        // Reset isHit so Fire1 has to be pressed again before the next time
        isHit = false;
    }
}

Upvotes: 1

Related Questions