shogitai
shogitai

Reputation: 1961

Force mode working only on Y axis Unity3D

I'm learning how to use Unity3D.

I have this scene where the elements are two PNG images (two black circles) to which I have associated the Rigidbody property (without gravity).

enter image description here

enter image description here

With a script I have associated the controller of the horizontal axis and it works: I can control the central circle with the keyboard.

Now I'm trying to associate a constant force. My script is as follows. But it only works along the Y axis. I can not make it work along the horizontal axis.

The script is:

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

public class CircleController : MonoBehaviour {

    float MaxSpeed = 10f;
    Rigidbody rigid2D;
    public Vector3 tensor;

    // Use this for initialization
    void Start()
    {
        rigid2D = GetComponent<Rigidbody>();
        rigid2D.AddForce(new Vector3(0,10,0), ForceMode.Force);
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        float move = Input.GetAxis("Horizontal");
        rigid2D.velocity = new Vector2(move * MaxSpeed, rigid2D.velocity.y);
    }
}

Can someone help me to understand why I can not put a force along that axis?

In particular, when I execute the script with this instruction: rigid2D.AddForce(new Vector3(0,10,0), ForceMode.Force);, I see the central circle moving towards the other. This is right.

enter image description here

Instead, when I execute it with this instruction rigid2D.AddForce(new Vector3(10,0,0), ForceMode.Force); the central circle remains stationary.

Upvotes: 1

Views: 847

Answers (1)

Hellium
Hellium

Reputation: 7356

You call the following line in the Start function (executed once)

rigid2D.AddForce(new Vector3(10,0,0), ForceMode.Force);

It applies a force to the rigidbody to the right by the given value (10). The Physics engine computes the acceleration to apply to the rigidbody and will automatically compute the velocity (speed) and new positions each frame.

However, in the FixedUpdate, you call the following lines

float move = Input.GetAxis("Horizontal");
rigid2D.velocity = new Vector2(move * MaxSpeed, rigid2D.velocity.y);

Here, you force the velocity of the rigidbody on the horizontal axis, overriding the value computed by the Physics engine. If you don't press the buttons defined in the Input manager, the circle will remain still on the horizontal axis since move is equal to 0.


When calling rigid2D.AddForce(new Vector3(0,10,0), ForceMode.Force);, the circle moves up, because rigid2D.velocity = new Vector2(move * MaxSpeed, rigid2D.velocity.y); keeps the velocity on the vertical axis.

Upvotes: 5

Related Questions