- Home /
Question by
StarlingSoftworksInteractive · Mar 29, 2017 at 07:50 AM ·
c#scripting problemscripting beginnerbeginnermovement script
How to move the object to where the object is already pointing to?
Hey guys, I created a script for my player, so he can rotate on the z axis on "Rotation" (a, d) and player can move left to right on Horizontal (Left Arrow, Right Arrow). I also set it so the player is automatically moving up. I am wondering if I rotated left or right on z axis, how am I able to move the player to that direction because right now when I rotate left or right, the player still moves straight up.
Here is my Code
// Player Speed
float speed = 450;
float forwardSpeed = 40;
float rotateSpeed = 100;
// Player Rigidbody
Rigidbody2D rb;
// Launch Button, Launch Button Gameobject and set launch to false
public GameObject launchButton;
Button lb;
bool launch = false;
void Start () {
// Get Rigidbody and button component from gameObject
rb = GetComponent<Rigidbody2D>();
lb = launchButton.GetComponent<Button>();
}
void FixedUpdate () {
// Set player movement controls
float Horizontal = Input.GetAxis("Horizontal");
float Rotation = Input.GetAxis("Rotation");
//Launch Button (on click go to LaunchButton method)
lb.onClick.AddListener(this.LaunchButton);
if (launch == true) // if launch equals true then
{
//move player upwards, left or right;
rb.velocity = new Vector3(Horizontal * speed, forwardSpeed, 0) * Time.deltaTime;
//rotate player left or right
transform.Rotate(0, 0, Input.GetAxis("Rotation") * rotateSpeed * Time.deltaTime);
}
}
Thanks guys for your help
Comment
Answer by UnityCoach · Mar 29, 2017 at 09:41 AM
Transform.Translate using Space.Self, or if you use Physics, RigidBody.AddRelativeForce.
By the way, if you use Physics, you may prefer to use Rigidbody.AddTorque()
over transform.Rotate()
.