Search code examples
c#unity-game-enginemove

unity how can I convert transform.position into physical movement?


In my code I move the player with transform.position but this creates problems with colliders and the physic of my game.

 transform.position = new Vector3(
                transform.position.x + touch.deltaPosition.x * multiplier,
                transform.position.y,
                transform.position.z + touch.deltaPosition.y * multiplier)

How can I convert this to velocity or some physical movement so that the speed get not effect?


Solution

  • In general as soon as there is a Rigidbody and collisions involved you should avoid two things:

    • Moving your object via the transform
    • Moving your object in Update

    Both breaks the physics.

    What you rather want to do is either directly update the Rigidbody.velocity. It is fine to do that in Update

    // If possible already reference via Inspector
    [SerializeField] private Rigidbody _rigidbody;
    
    private void Start()
    {
        if(!_rigidbody) _rigidbody = GetComponent<Rigidbody>();
    }
    
    private void Update()
    {
        ...
    
        _rigidbody.velocity = Vector3.right * touch.deltaPosition.x * multiplier 
            + Vector3.forward * touch.deltaPosition.y * multiplier;
        ...
    }
    

    The alternative is to separate the User input (Update) from the physics routine (FixedUpdate) and use MovePosition

    (assuming your code is executed in Update)

    private Vector3 targetPosition;
    
    // If possible already reference via Inspector
    [SerializeField] private Rigidbody _rigidbody;
    
    private void Start()
    {
        if(!_rigidbody) _rigidbody = GetComponent<Rigidbody>();
    
        targetPosition = transform.position;
    }
    
    private void Update()
    {
        ...
    
        targetPosition = _rigidbody.position 
            + Vector3.right * touch.deltaPosition.x * multiplier 
            + Vector3.forward * touch.deltaPosition.y * multiplier;
    
        ...
    }
    
    private void Update()
    {
        _rigidbody.MovePosition(targetPosition);
    }