- Home /
Simple C# Vector2D Moving Question
Hey There! I am having some problems creating a C# script to move my object in a 2D space using Vector2, this is how it looks at the moment, but it gives me a bunch of errors, in line 13. If i change "transform.Translate(Vector2...." to: "Vector2.Up" It works with no errors, but this does not work for me as my object is rotating.
using UnityEngine;
using System.Collections;
public class PControl : MonoBehaviour {
public float moveSpeed = 10f;
void Update () {
if(Input.GetKey(KeyCode.UpArrow))
{
transform.Translate(Vector2(0, 1) * moveSpeed * Time.deltaTime);
Debug.Log ("UP");
}
}
}
Any help is appreciated!
Try transform.Translate(new Vector3(0, 1,0) * moveSpeed * Time.deltaTime); or Try
transform.Translate(Vector3(0, 1,0) moveSpeed Time.deltaTime);
Translate is changing the position of an object using Vector3. I would recommend you to not use Translate because it is working in the same way as you would just change position values in the editor. Try to use rigidbody2D.velocity or rigidbody2D.AddForce().
@DajBuzi Thank you! I managed to get it working even better with .AddForce, thanks for the help :)
Answer by robertbu · Feb 09, 2014 at 05:27 PM
You need the 'new' keyword in front of Vector2() in C#. Line 13:
transform.Translate(new Vector2(0, 1) * moveSpeed * Time.deltaTime);
Note that the Vector2 class has a Vector2.up, so you can do:
transform.Translate(Vector2.up * moveSpeed * Time.deltaTime);