Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Rigidbody2D arm won't move when player is moving

Discussion in 'Physics' started by M3ntalll, Aug 27, 2020.

  1. M3ntalll

    M3ntalll

    Joined:
    Jul 1, 2020
    Posts:
    8
    I am currently developing a 2D Dungeon Crawler game. If you take a look at the screenshots, the aiming mode I'm trying to create is a detached arm from the body that will follow your cursor wherever it is. It is currently working for the most part, but it stops working whenever the player is moving. I cannot aim the arm whenever I am in the middle of moving the Player, but when I stop aiming I can aim the arm. Any solutions?

    Here is a look at my Player code and Arm code just in case:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerMovement : MonoBehaviour
    6. {
    7.  
    8.     public float moveSpeed = 5f;
    9.  
    10.     public Rigidbody2D rb;
    11.  
    12.     Vector2 movement;
    13.  
    14.     // Update is called once per frame
    15.     void Update()
    16.     {
    17.         movement.x = Input.GetAxisRaw("Horizontal");
    18.         movement.y = Input.GetAxisRaw("Vertical");
    19.     }
    20.  
    21.     void FixedUpdate()
    22.     {
    23.         rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);
    24.     }
    25. }
    26.  
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class ArmMovement : MonoBehaviour
    6. {
    7.  
    8.     public Rigidbody2D armrb;
    9.     public Camera cam;
    10.  
    11.     Vector2 mousePos;
    12.  
    13.     // Update is called once per frame
    14.     void Update()
    15.     {
    16.         mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
    17.     }
    18.  
    19.     void FixedUpdate()
    20.     {
    21.         Vector2 lookDir = mousePos - armrb.position;
    22.         float angle = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg - 10f;
    23.         armrb.rotation = angle;
    24.     }
    25. }
    26.  
     

    Attached Files:

  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,121
    You should choose a movement method and use only one. In your case, you're using MovePosition so this is presumably a Kinematic body-type so use Rigidbody2D.MoveRotation to rotate.