Search Unity

How do you move Rigidbody towards a position while using Physics?

Discussion in 'Scripting' started by ynm11, Jul 8, 2021.

  1. ynm11

    ynm11

    Joined:
    Jul 6, 2021
    Posts:
    57
    I'm trying to move my Rigidbody player towards a gameobject's (named highCube) position; I'd like physics to be used so that they collide with any objects that may be in their path.

    So far I've tried:

    private void FixedUpdate()
    {
    //rb.MovePosition(rb.position + highCube.transform.position * Time.deltaTime * moveSpeed);

    //rb.MovePosition(Vector3.Lerp(rb.position, highCube.transform.position, moveSpeed * Time.deltaTime));
    }

    but neither of these approaches are moving the player at all, actually. What might be going wrong? What should I try? Thanks!
     
  2. gorbit99

    gorbit99

    Joined:
    Jul 14, 2015
    Posts:
    1,350
    Is you rigidbody kinematic by any chance?
     
  3. ynm11

    ynm11

    Joined:
    Jul 6, 2021
    Posts:
    57
    Non-kinematic in fact. I think it has to be non-kinematic in order to have correct physics interactions but I'm not sure.
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,736
    As long as you code like that it's gonna be a constant struggle when stuff doesn't work.

    Break it out into temporary variables and add tons of debug spew to figure out what is happening.

    It could even be as trivial as moveSpeed is zero, or negative, or super-small. How would you know with those hairy lines of code?

    How to break down hairy lines of code:

    http://plbm.com/?p=248

    Break it up, practice social distancing in your code, one thing per line please.

    Once it is all broke out nicely, to help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

    Doing this should help you answer these types of questions:

    - is this code even running? which parts are running? how often does it run? what order does it run in?
    - what are the values of the variables involved? Are they initialized? Are the values reasonable?

    Knowing this information will help you reason about the behavior you are seeing.

    You can also put in Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene

    You could also just display various important quantities in UI Text elements to watch them change as you play the game.

    If you are running a mobile device you can also view the console output. Google for how on your particular mobile target.

    Here's an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

    https://forum.unity.com/threads/coroutine-missing-hint-and-error.1103197/#post-7100494
     
    ynm11 likes this.