What is wrong with this script?
This is my 5th augmentation of some code to make a cube move. That's it, just move in any direction at any speed and I have been ripping my hair out for 2 days trying to get it to work. I have copied and pasted Unity's own, 2016 updated code and it doesn't even come close to working. This is my best variation with what I think is the most comprehensible error message... \\ CS1501: No overload for method 'AddForce takes '4' arguments \\ I've looked it up and it looks like it happens when you improperly call a variable although I don't see where this is happening. I even removed all the variables including void Move() and it still gave me that error. Here is the code...
using UnityEngine;
using System.Collections;
public class SimpleMovement : MonoBehaviour {
public float thrust = 10;
public Rigidbody2D rb2D;
void Start ()
{
rb2D = GetComponent<Rigidbody2D> ();
}
void Move ()
{
rb2D.AddForce(0, thrust, 0 , ForceMode.Impulse);
}
void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
Move();
Debug.Log ("I hate C#");
}
}
And please, don't just copy and paste Unity Docs in a lazy response, there is nothing left for me there...
Answer by OutOfRam · Oct 28, 2016 at 05:04 PM
Hey there,
This should be pretty simple, the first argument that you have set to 0 in the addForce function is an int value, but the function requires a vector2 value. This means it requires both an x and y value. Also you only need the force and force mode, it should only be 2 arguments try this;
public Vector2 thrust;
public Rigidbody2D rb2D;
void Start ()
{
thrust = new Vector2(1,4);//thrust will be 4 times as strong in the y af it is in the x
rb2D = GetComponent<Rigidbody2D> ();
}
void Move ()
{
rb2D.AddForce(thrust, ForceMode2D.Impulse);
}
void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
Move();
Debug.Log ("I hate C#");
}
I hope this helps!
Answer by Zynek · Oct 28, 2016 at 04:55 PM
Please read the documentation a little more carefully https://docs.unity3d.com/ScriptReference/Rigidbody2D.AddForce.html
The method takes 2 arguments: Vector2 force, ForceMode2D mode = ForceMode2D.Force
"0, thrust, 0" is not a Vector2 !!!
Here´s how you define a Vector2:
new Vector2(x,y);
where x and y are float variables that specify direction in x,y axis.
Answer by tiggy02 · Oct 28, 2016 at 05:16 PM
Your problem is that you are not specifying that you are moving in a Vector2 you are trying to move in a Vector3 with specifying that it is a Vector3.
void Move () { rb2D.AddForce(new Vector2(thrust, 0), ForceMode.Impulse); }