Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

[C#] How To Make an Object Anchor On Another

Discussion in 'Scripting' started by BsseeJ, Jun 21, 2014.

  1. BsseeJ

    BsseeJ

    Joined:
    Mar 12, 2014
    Posts:
    20
    Hello Unity Forum

    I am attempting to make a mechanic in my game where a weapon will be part of my player character object in such a way that it floats around it depending on where the mouse inputposition is.

    (Image of Player and Weapon)
    http://imgur.com/akOxcOX

    The idea is that if the mouse is straight above the player it will face straight up and stay above the character object, while if let's say the mouse is to the direct right of the character object the weapon object will follow and face that direction as well while maintaining the distance from the player object. I also would like the distance to be at a constant of 3 at all times. I don't want the weapon object too far away from the player or too close.



    I have been working on it and I wrote a script that works to a certain extent. It has the weapon object follow the mouse and the player on either sides, the problem is if you drag the mouse out of the max distance zone the weapon object hops back and forth.

    Code (CSharp):
    1.  
    2.  
    3. public class swordMovement : MonoBehaviour {
    4.    public GameObject playerC;
    5.  
    6.    void Start (){
    7.      }
    8.  
    9.    void Update () {
    10.  
    11.  
    12.  
    13.  
    14.      float distance = Vector2.Distance (gameObject.transform.position, playerC.transform.position);
    15.      if (distance > 3f) {
    16.        var gPosY = gameObject.transform.position.y;
    17.        var gPosX = gameObject.transform.position.x;
    18.        var plPosY = playerC.transform.position.y;
    19.        var plPosX = playerC.transform.position.x;
    20.        Vector2 gPos = new Vector2(gPosX, gPosY);
    21.        Vector2 plPos = new Vector2 (plPosX, plPosY);
    22.        gameObject.transform.position = Vector2.Lerp(gPos,plPos, 200 * Time.deltaTime);
    23.      }
    24.      else
    25.      {
    26.  
    27.        // get wepaon to follow mouse rotation
    28.        Vector3 realMousePos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
    29.        Vector3 artiMousePos = new Vector3 (realMousePos.x, realMousePos.y, -2);
    30.        transform.position = Vector3.Lerp (transform.position, artiMousePos, 5f * Time.deltaTime);
    31.        // Get weapon to follow mouse rotation
    32.        Vector3 toMousePosition = playerC.transform.position - transform.position;
    33.        transform.up = toMousePosition;
    34.      }
    35.    }
    36. }
    37.  
    Thanks for any help!
     
    Last edited: Jun 22, 2014
  2. Deequation

    Deequation

    Joined:
    Jan 2, 2014
    Posts:
    16


    Here is an example code, illustrating how to adjust the position and rotation of a floating object (the weapon) around a player and have it follow the mouse position at a fixed distance. This is done by calculating a directional vector between the player and the mouse position. You should note that this code relies heavily on the camera setup for orientation, displacement and type, so you might have to adjust it to fit your specific setup. I used the default camera for this, and the reference camera main is a reference to the main camera tag, if you aren't using that, you have to replace the reference manually. I also have a reference to the player transform called 'ThePlayer' but I excluded it from the example code.



    [01] Setting the position of the weapon to follow the mouse at a fixed distance:


    The first thing we do is to create a directional vector, by taking the mouse position minus the player position. To get themouse position in world space, we have to convert it from screen space to world space, you can lookup how this is done in the reference below, as this is where your camera setup will be important for the setup. Then by normalizing this direction and multiplying by the distance, we can calculate the position of the weapon in world space, relative to the player.

    Code (CSharp):
    1. ..
    2. Vector3 Cursor_Screen = new Vector3(Input.mousePosition.x, Input.mousePosition.y, ThePlayer.position.z - Camera.main.transform.position.z);
    3. Vector3 Cursor_World  = Camera.main.ScreenToWorldPoint(Cursor_Screen);
    4. Vector3 Direction     = (Cursor_World - ThePlayer.position).normalized * 1.5f;
    5.  
    6. transform.position = ThePlayer.position + Direction;
    7. ..




    [02] Rotating the weapon so it matches the direction:


    Now that the weapon is being circled around the player at a fixed distance, we also want to rotate it towards the mouse, so we need to apply a rotation to the weapon transform, that matches the direction between the player and the mouse in world space. Here I made use of the LookRotation function that takes a directional vector - since we already calculated this in the previous code. Then we just overwrites the rotation and it then points in the same direction.

    Code (CSharp):
    1. ..
    2. transform.rotation = Quaternion.LookRotation(transform.position + Direction);
    3. ..




     
    Last edited: Jul 22, 2015
    Thoaril and sam_fisher3000 like this.
  3. BsseeJ

    BsseeJ

    Joined:
    Mar 12, 2014
    Posts:
    20
    This almost works perfectly, I'm not entirely sure how it works but there seems to be two things not working perfectly. The weapon seems to be shrinking and extending depending on where the mouse is and after a while it gets stuck looking toward the top right or top left although it will turn as normal. This seems to be dependent on where the player is on the screen Here is an image of this

    (Player Character moved to farthest right side)
    http://imgur.com/AhHBgmU,rHG0Q8P
    (Player Character moved to farthest left side)
    http://imgur.com/Qa6kD4r

    it probably has to do with what you were saying about the camera, I only have one in the scene and I'm using it. Also keep in mind that the weapon object is a 2D sprite as this is a 2D game.

    I don't really understand how your code works, I'll have to spend more time on those documents. Thanks for the help my weapon mechanic is doing a lot better like this then how it had been. I simply have to get the sprite to not extend or shrink and it will be set.

    Thanks again from Jesse "BsseeJ" Bergerstock