Fixed force in direction of touch.

Hello, I’m making a 2D game based in space. Right now I use AddForce to push my rigidbody in the direction of where I touch. My problem is that the force is greater the further I touch from my rigidbody. I’ve tried using normalise but I still have the same problem. I want to be able to have my rigidbody move at a fixed value force in the direction of where I touch so how far I touch has no effect.

Here’s my code:
C#

    public float Speed = 10;

    private Vector3 force;
    private Vector3 direction;
    private Vector3 touchPosition;
    private Vector3 touchPosAtScreen;

	// Update is called once per frame
	void Update () 
    {
        foreach (Touch touch in Input.touches)
        {
            if (touch.tapCount < 2 && touch.phase == TouchPhase.Ended)
            {
                touchPosition = touch.position;
                touchPosAtScreen = Camera.main.ScreenToWorldPoint(touchPosition);

                direction = (touchPosAtScreen - rigidbody.transform.position);

                force = (direction.normalized * Speed);

                rigidbody.AddForce(force);

                Debug.Log("Force = " + force);
            }
        }

Thanks,

Giles.

You have an issue and a potential issue with this code. The main issue is that you are not modifying the ‘z’ parameter of touchPosition before calling ScreenToWorldPoint(). The ‘Z’ position is the distance in front of the camera. Without specifying a ‘z’ value (i.e. having a ‘z’ value of 0), you are always going to get the camera position back from the call. The second issue is that you are processing all touches. That means if you have multiple fingers, you are going to get a AddForce() for each touch. Note I believe the velocity to be the same no matter where you touch, but since you are not specifying a ‘z’ parameter to the ScreenToWorldPoint() some of that velocity may be in a direction that is not as apparent. To verify, add a Debug.Log(rigidbody.velocity.magnitude); to your update.