I have this code: Code (CSharp): using UnityEngine; using System.Collections; public class mechanic : MonoBehaviour { public float speed = 10.0F; void Start () { } void Update() { Vector2 dir = Vector2.zero; dir.x = Input.acceleration.x; if (dir.sqrMagnitude > 1) dir.Normalize(); dir *= Time.deltaTime; Rigidbody2D.AddForce(Vector2 (dir * speed, 0)); } } And im getting this error Code (CSharp): Assets/mechanic.cs(21,29): error CS0120: An object reference is required to access non-static member `UnityEngine.Rigidbody2D.AddForce(UnityEngine.Vector2, UnityEngine.ForceMode2D)' Why?
There are plenty in the documentation for GetComponent. You would use GetComponent<Rigidbody2D>() instead of just Rigidbody2D
Code (CSharp): Changed: GetComponent<Rigidbody2D>().AddForce(Vector2 (dir * speed, 0)); Error: Code (CSharp): Assets/scripts/mechanic.cs(21,54): error CS0119: Expression denotes a `type', where a `variable', `value' or `method group' was expected Assets/scripts/mechanic.cs(21,45): error CS1502: The best overloaded method match for `UnityEngine.Rigidbody2D.AddForce(UnityEngine.Vector2)' has some invalid arguments Assets/scripts/mechanic.cs(21,45): error CS1503: Argument `#1' cannot convert `object' expression to type `UnityEngine.Vector2'
If you use Unity4 you can just write rigidbody2D with lowercase 'r' and not uppercase 'R'. For Unity5 you should use GetComponent<Rigidbody2D>()
Code (CSharp): using UnityEngine; using System.Collections; public class mechanic : MonoBehaviour { public float speed = 10.0F; void Start () { } void Update() { Vector2 dir = Vector2.zero; dir.x = Input.acceleration.x; if (dir.sqrMagnitude > 1) dir.Normalize(); dir *= Time.deltaTime; GetComponent<Rigidbody2D>().AddForce(new Vector2 (dir * speed, 0)); } }
You're trying to create a new Vector2 using an entire vector as the X component. I think what you're looking for is: Code (CSharp): GetComponent<Rigidbody2D>().AddForce(new Vector2 (dir.x * speed, 0));
Thanks Limeoats. That makes the errores disappear. But now is new problem starting to appear. The script is attached to a ball with rigidbody2d. And when i move arround with the ball (By moving the screen) the ball start to go though 2D colliders. Its like its squeezses though the objects. How can i improve the mechanics?
It depends on what you're going for. You can add more physics properties to the ball to slow it down when it goes through, or tighten the space so it can't fit through if that is what you're going for. It all depends on what you're trying to do.