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\$
4
  • \$\begingroup\$ Don't happen to have any constraints set, do you? \$\endgroup\$
    – House
    Jun 15, 2017 at 20:56
  • \$\begingroup\$ @Byte56, no. I checked right now, there are no any constraints. \$\endgroup\$
    – some1 here
    Jun 15, 2017 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\$
    – some1 here
    Jun 15, 2017 at 21:11
  • \$\begingroup\$ Possible solution for this: forum.unity.com/threads/… Answer 8 \$\endgroup\$
    – Hernando N
    Jun 3, 2021 at 23:15

2 Answers 2

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\$
2
  • \$\begingroup\$ Reason for the downvote? \$\endgroup\$
    – Turms
    Jun 18, 2017 at 12:58
  • \$\begingroup\$ The screenshot shows a non-zero running speed, and running speed is not set from the object's initial velocity in any code we can see here. \$\endgroup\$
    – DMGregory
    Feb 24, 2021 at 21:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .