3
\$\begingroup\$

My problem is when I am pressing A or D, the player does not move. It is very stupid I am sure as you are, but I can not find what I am doing wrong. I could have achieved the effect I want with the help of transform.translate(), but I would like immensely to get what is misunderstood by me in the case.

Here is my code:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MovementController : MonoBehaviour
{
    public float runningSpeed;
    public Rigidbody2D playerBody;

    void Update ()
    {
        if(Input.GetKey("d"))
        {
            print("Right");
            moveRight();
        }
        else if (Input.GetKey("a"))
        {
            print("Left");
            moveLeft();
        }
    }

    private void moveLeft()
    {
        playerBody.AddForce(Vector2.left * (runningSpeed * Time.deltaTime), ForceMode2D.Force);
    }

    private void moveRight()
    {
        playerBody.AddForce(Vector2.right * (runningSpeed*Time.deltaTime), ForceMode2D.Force);
    }
}

Here is a screenshot of my editor:

enter image description here

\$\endgroup\$
  • \$\begingroup\$ Don't happen to have any constraints set, do you? \$\endgroup\$ – MichaelHouse Jun 15 '17 at 20:56
  • \$\begingroup\$ @Byte56, no. I checked right now, there are no any constraints. \$\endgroup\$ – ohidano Jun 15 '17 at 20:59
  • \$\begingroup\$ Tried using Vector3 instead of Vector2 does not work either. Tried using AddForce() without second parameter does not work as well. \$\endgroup\$ – ohidano Jun 15 '17 at 21:11
0
\$\begingroup\$

Here is a solution. Unity considers Mass of 10 to be very large. First I tried to apply a very great force, like 10 thousand and noticed that RigidBody2D actually moves a little bit. Then I decreased Mass to 0.5 and voila I got a needed effect!

\$\endgroup\$
-1
\$\begingroup\$

Your force depends linearly on "runningSpeed", so if the initial velocity is zero, it will stay zero. Try to give a different intial speed or change your force.

\$\endgroup\$
  • \$\begingroup\$ Reason for the downvote? \$\endgroup\$ – Turms Jun 18 '17 at 12:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.