How do you create a 2D player movement script?
Hello everyone! I am a little new to unity C# coding (I know C# very well though) and I have been creating a 2d sandbox, Right now I have all of my sprites in, but I need to know how to make a player controller, I already have most of the script, but I am stuck at the moving part (commented as //stuck here), Thanks for any help in advance. (p.s. I know Vector3 and Vector2 as I did them in one of my coding classes a while back)
using UnityEngine;
using System.Collections;
public class PlayerMover : MonoBehaviour {
//init variables
public GameObject target = this.GetComponent(); //also an error here.
public float Speed = 0f;
public float move = 0f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
KeyCode RightKey = KeyCode.D; //shortcut
KeyCode LeftKey = KeyCode.A; //shortcut
if(Input.GetKey (RightKey)) //when Right Key pressed (D)
{
//stuck here
}
else if(Input.GetKey (LeftKey)) //when Left Key pressed (A)
{
//stuck here
}
}
}
Answer by _Game_Dev_Dude_ · Nov 19, 2015 at 02:26 PM
There are two ways of solving this. Using unity physics or handling the movement calculations yourself and editing the transform. I would suggest using unity's built in 2D physics.
To get you started, you need to add a Rigidbody2D component to your player object. Then in this script where you commented "stuck here", you will use the following :
GetComponent<Rigidbody2D>().AddForce( movementForce);
Hope this helps!
@Game_Dev_Dude I get an error of it saying: The type or namespace RigidBody2D could not be found, I even put the rigid body inside the 2d player sprite.
Sorry typo in my original comment. The 'B' in RigidBody should be lower case.
GetComponent<Rigidbody2D>().AddForce( movementForce);
No errors, but it dosen't work still
//snip of the code
void Update () {
$$anonymous$$eyCode Right$$anonymous$$ey = $$anonymous$$eyCode.D; //shortcut
$$anonymous$$eyCode Left$$anonymous$$ey = $$anonymous$$eyCode.A; //shortcut
if(Input.Get$$anonymous$$ey (Right$$anonymous$$ey)) //when Right $$anonymous$$ey pressed (D)
{
GetComponent<Rigidbody2D>().AddForce(Vector2.right);
}
else if(Input.Get$$anonymous$$ey (Left$$anonymous$$ey)) //when Left $$anonymous$$ey pressed (A)
{
GetComponent<Rigidbody2D>().AddForce(Vector2.left);
}
}
}
$$anonymous$$ake sure your rigid body does not have the "is$$anonymous$$inematic" checkbox checked in the inspector.
$$anonymous$$ake sure the mass on your rigid body is something small like 1.
Also those vectors are very small in comparison with the world. Try multiplying them by 100 and see if they still do nothing.
AddForce(Vector2.right * 100);
@Game_Dev_Dude Sorry about late reply, Even multiplying by 1000 dosen't work.