How do i make my player follow my finger when i start to pull it

im trying to make a 2D maze game, its simple but i need to make the player follow my finger at screen, i just made the player go and follow my finger to where i put my finger on screen, but i just want it to start following only when i'm with my finger over the player but it just doesn't works.

I'm using this script atm but isn't working as i want :X

void Update() {
        if(Input.GetMouseButton(0)) {
            Vector3 pos = Input.mousePosition;
            pos.z = distanceFromCamera;
            pos= cam.ScreenToWorldPoint(pos);
            rb.velocity = (pos-square.position)*velocity;
        }
        if(Input.GetMouseButtonUp(0)) {
            rb.velocity = Vector3.zero;
        }
}

Tried now this script:

 using UnityEngine;
 using System.Collections;
 
[RequireComponent(typeof(MeshCollider))]
 
public class DraggingObject : MonoBehaviour 
{
    private Vector3 screenPoint;
    private Vector3 offset;
 
    void OnMouseDown() {
        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() {
        Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
        Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
        transform.position = curPosition;
    }

}

It drags like i want, but when i need to make a collision it doesn't work, just pass like no collision has been added to the game.

Upvotes: -1

Views: 51

Answers (1)

Ruzihm
Ruzihm

Reputation: 20259

I'd just use IDragHandler to make this easy:

public class FollowFinger : MonoBehaviour, IDragHandler
{
    // ...

    public void OnDrag(PointerEventData eventData)
    {
        Vector3 pos = eventData.position
        pos.z = distanceFromCamera;
        pos= cam.ScreenToWorldPoint(pos);
        rb.velocity = (pos-square.position)*velocity;
    }
}

You might need to add a Physics2DRaycaster to your camera (or PhysicsRaycaster if you're using 3d).

You might also want to make the collider (whatever kind that is appropriate) for your player a bit larger than they appear so the player can drag their finger further away.

See here for more guidance.

Upvotes: 1

Related Questions