Question

So, I'm developing a game pretty much like bowling in Unity3D.

The user has to pickup an object and throw it, just like in bowling. The user has a limited area to throw it.

My question is: How do I calculate the vector to apply in the rigidbody? I read in a question like this that I have to subtract the atualposition to the lastposition to get the vector. And I get it. But, how do I get the lastposition? I mean, the user could be sliding the gameObject from one spot to another until he decides to throw it. You can verify what I mean in the Glow Hockey game:

https://play.google.com/store/apps/details?id=com.natenai.glowhockey

https://itunes.apple.com/pt/app/glow-hockey-2-free/id346453382?mt=8

And this is pretty much what I'm trying to do.

Was it helpful?

Solution

Are you developing a mobile game, i.e. do you have touch input or mouse input?

You basically need a gesture recognizer. You can write one for yourself and always track the touch/mouse position from the last frame and then interpret the cursor movement. You will want to interpret whether the user has made a drag or a swipe gesture and use that to add forces to your GameObjects.

There are also gesture interpreters available in the asset store. Just search for "gestures" or "touch gestures" there: https://www.assetstore.unity3d.com/#/search/gestures%20touch

OTHER TIPS

using UnityEngine;

public class DragThrow : MonoBehaviour
{

    public GameObject hoop;
    private Rigidbody rigidbody;
    private Vector3 screenPoint;
    private Vector3 offset;
    private Vector3 oldMouse;
    private Vector3 mouseSpeed;
    public float speed = 5;

    void Start()
    {
        rigidbody = GetComponent<Rigidbody>();
    }

    void OnMouseDown()
    {
        oldMouse = Input.mousePosition;
        screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
        offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
    }


    void OnMouseDrag()
    {
        var curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
        Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) - offset;
        transform.position = curPosition;

    }

    void OnMouseUp()
    {
        mouseSpeed = (oldMouse - Input.mousePosition);
        rigidbody.AddForce(mouseSpeed * speed * -1, ForceMode.Force);

    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top