Search Unity

Question Cant figure out why this (simple?) movement code does not work? (Ruby's Adventure 2D tutorial)

Discussion in '2D' started by Felixj93, Jun 16, 2020.

  1. Felixj93

    Felixj93

    Joined:
    May 2, 2020
    Posts:
    19
    Hey, when implement the following code to my script, my character freezes:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class RubyController : MonoBehaviour
    6. {
    7.     public Rigidbody2D rb2d;
    8.     float horizontal;
    9.     float vertical;
    10.     public float speed = 5f;
    11.  
    12.     private void Start()
    13.     {
    14.         rb2d = GetComponent<Rigidbody2D>();
    15.     }
    16.  
    17.     private void Update()
    18.     {
    19.         horizontal = Input.GetAxis("Horizontal");
    20.         vertical = Input.GetAxis("Vertical");
    21.     }
    22.  
    23.     private void FixedUpdate()
    24.     {
    25.         Vector2 position = this.rb2d.position;
    26.         position.x = position.x * speed * horizontal * Time.deltaTime;
    27.         position.y = position.y * speed * vertical * Time.deltaTime;
    28.  
    29.         rb2d.MovePosition(position);
    30.     }
    31. }
    but if I type in this it works:

    Code (CSharp):
    1. public Rigidbody2D rigidbody2d;
    2. public float speed = 5.0f;
    3. Vector2 movement;
    4.  
    5. void Start()
    6. {
    7.     rigidbody2d = GetComponent<Rigidbody2D>();
    8. }
    9.  
    10. void Update()
    11. {
    12.     movement.x = Input.GetAxis("Horizontal");
    13.     movement.y = Input.GetAxis("Vertical");
    14. }
    15.  
    16. private void FixedUpdate()
    17. {
    18.     rigidbody2d.MovePosition(rigidbody2d.position + movement * speed * Time.deltaTime);
    19. }
    20.  
    Im very curious why?
     
  2. Felixj93

    Felixj93

    Joined:
    May 2, 2020
    Posts:
    19
    Solved!
     
  3. Chris-Trueman

    Chris-Trueman

    Joined:
    Oct 10, 2014
    Posts:
    1,261
    So people know how you solved it.
    Code (CSharp):
    1. position.x = position.x + horizontal * speed * Time.deltaTime;
    2. position.y = position.y + vertical * speed * Time.deltaTime;
    You have to add the input values, not multiply them.
     
    Felixj93 likes this.