Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

2d - SpringJoint2d not working properly

Discussion in '2D' started by wtadlock, Jun 11, 2017.

  1. wtadlock

    wtadlock

    Joined:
    Aug 1, 2016
    Posts:
    15
    Good morning all,

    I was following a tutorial on youtube from Brackey's,
    on how to make an Angry Birds Style game. I really just needed the launcher information. I was able to get his code to work to launch the item, but I want to restrain it to dragging on the X axis only. I did a lot of googling and got it to work with a 3d object, but when I modified the code for a sprite, it stopped working. What I mean by that is, I can drag it along the X axis only, but when I let go, it no longer launches. It just sites there. Below is my code, any assistance would be greatly appreciated.

    If I uncomment out the following
    //rb.position = Camera.main.ScreenToWorldPoint(Input.mousePosition);​
    andn comment out the following
    Vector2 rbPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    transform.position = new Vector2(rbPosition.x, transform.position.y);​

    it works, but moves on the Y axis as well. I have tried using Vector3 as well. And locking the rigidbody2d on the Y axis is not an option as my sprite needs to travel on that axis after release.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class LaunchPlayer2D : MonoBehaviour {
    6.  
    7.     public Rigidbody2D rb;
    8.  
    9.     public float releaseTime = .15f;
    10.  
    11.     private bool isDragging = false;
    12.  
    13.     private void Update()
    14.     {
    15.         if (isDragging)
    16.         {
    17.             //rb.position = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    18.             Vector2 rbPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    19.             transform.position = new Vector2(rbPosition.x, transform.position.y);
    20.         }
    21.     }
    22.  
    23.     private void OnMouseDown()
    24.     {
    25.         isDragging = true;
    26.         rb.isKinematic = true;      
    27.     }
    28.  
    29.     private void OnMouseUp()
    30.     {
    31.         isDragging = false;
    32.         rb.isKinematic = false;
    33.         StartCoroutine(Launch());
    34.  
    35.     }
    36.  
    37.     IEnumerator Launch()
    38.     {
    39.         yield return new WaitForSeconds(releaseTime);
    40.         GetComponent<SpringJoint2D>().enabled = false;
    41.     }
    42. }
    43.  
    Thanks,

    Walter