Search code examples
c#unity3d-2dtools

Stop sprite from bouncing


I am making a simple puzzle game on the Unity platform. First, I tested some simple physics on scratch and then wrote it in C#. But for some reason, some of the code isn't producing the same effect. In scratch, the codeenter image description here makes the sprite do exactly what I want; go towards the mouse, slow down, then stop on the mouse. However, (what I presume to be) the same code in Unity makes the sprite go crazy and never stop.

UPDATE

It definitely is cause #2. It turns out the sprite is bouncing off other bounding boxes, causing the velocity to change drastically. It would work with smaller values, except I have gravity. My new question is there any way to stop the sprite from bouncing?

Vector2 CalcHookPull(){
    //code for finding which hook and force
    //find if mouse pressed
    if (Input.GetMouseButton(0))
    {
        //check if new hook needs to be found
        if (!last){
            Vector2 mypos = new Vector2(transform.position.x, transform.position.y);
            Vector2 relmousepos = new Vector2(Camera.main.ScreenToWorldPoint(Input.mousePosition).x-transform.position.x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y-transform.position.y);
            //player is on layer 8, don't want to check itself
            int layermask = ~(1<<8);
            RaycastHit2D hit = Physics2D.Raycast(mypos, relmousepos, Mathf.Infinity, layermask);
            maybeHook = hit.collider.gameObject;
        }
        if(maybeHook.tag == "hook"){

            float hookx = maybeHook.transform.position.x;
            float hooky = maybeHook.transform.position.y;
            float myx = transform.position.x;
            float myy = transform.position.y;

            //elasticity = 30

            float chx = (hookx - myx) / (5f + 1f/3f);
            float chy = (hooky - myy) / (5f + 1f/3f);

            float curchx = GetComponent<Rigidbody2D> ().velocity.x;
            float curchy = GetComponent<Rigidbody2D> ().velocity.y;

            Vector2 toChange = new Vector2 (curchx * 0.3f + chx, curchy * 0.3f + chy);

            Debug.Log(toChange);
            last = Input.GetMouseButton (0);

            return toChange;

        } else{
            last = Input.GetMouseButton (0);
            return new Vector2(0,0);
        }
    } else {
        last = Input.GetMouseButton (0);
        return new Vector2 (0, 0);
    }

}

Possible differences:

  1. Vectors work differently that xy changes (doubtful)
  2. The bounding box is not allowing the sprite to go all the way to the center of the hook object. (likely, but don't know how to fix)
  3. I copied the code wrong (unlikely)

Any help is appreciated, thanks!


Solution

  • I was being stupid. There is already something for this. Should have thought it through more. http://docs.unity3d.com/Manual/class-PhysicsMaterial2D.html