S
S
Sergo Zar2021-11-15 23:00:53
Unity
Sergo Zar, 2021-11-15 23:00:53

How to do drag and drop with "magnetize"?

I'm trying to make the red squares, when dragged over the white ones, "stick" to them for a fraction of a second (well, it won't be like the player has moved a part of the square..). But it turns out so far, as on the record ( https://www.youtube.com/watch?v=WPLX8jlX72k )

my move code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class drag : MonoBehaviour
{
    private Vector3 offset;
    private int score = 1;
    
    //public float distance = 1f;
    //public LayerMask mask;

    /*void FixedUpdate(){
        RaycastHit2D hit = Physics2D.Raycast(transform.position, -Vector2.left);
        Debug.DrawRay(transform.position, -Vector2.left * distance);
        
        if (hit.collider != null){
            Debug.Log(hit.collider.name);
        }
    }*/
    void OnMouseDown(){
        if (score == 1){
            offset = gameObject.transform.position - 
            Camera.main.ScreenToWorldPoint(
                new Vector3(Input.mousePosition.x, Input.mousePosition.y, -10.0f));
        }
    }
 
    void OnMouseDrag(){
        if (score == 1){
            Vector3 newPosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, -10.0f);
            transform.position = Camera.main.ScreenToWorldPoint(newPosition) + offset;
        }
    }

    void OnTriggerEnter2D(Collider2D other){
        if(other.gameObject.GetComponent<objTags>()){
            List<string> tags = other.gameObject.GetComponent<objTags>().tags;
            bool isNorm = false;
            
            foreach (string tag in tags){
                if (tag.Equals("norm"))
                    isNorm = true;
            }
            
            if (isNorm){
                Debug.Log(other.gameObject.transform.position);
                transform.position = new Vector3(other.gameObject.transform.position.x, 
                    other.gameObject.transform.position.y, transform.position.z);
                StartCoroutine(dragPause());
            }
        }
    }

    IEnumerator dragPause(){
        // while (true){
            score = 0;
            yield return new WaitForSeconds(0.1f);
            score = 1;
        // }
    }
}

What am I doing wrong?

ps Perhaps something needs to be clarified; ask

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nekit Medvedev, 2021-11-16
@NIKROTOS

You can shift in increments of a cell, if this does not give the desired effect, see the information on delays:
https://docs.unity3d.com/ScriptReference/WaitForSe...
https://legkovopros.ru/questions/1428/dobav-te -vre...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question