Reputation: 129
I'm trying to move an object by doing the following :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed;
// Update is called once per frame
void Update()
{
float horznotalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
Vector3 movment = new Vector3(horznotalInput,0,verticalInput);
transform.Translate(movment * Time.deltaTime *speed);
}
}
But something weird happens to the object's movement.
when pressing on "a" key the object goes up
"d" goes down.
"w" goes right
and "s" goes left.
When I'm changing it to the following:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed;
// Update is called once per frame
void Update()
{
float horznotalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
float newHorizontalPosition = transform.position.x + horznotalInput * Time.deltaTime;
float newVerticalPosition = transform.position.z + verticalInput * Time.deltaTime;
transform.position = new Vector3(newHorizontalPosition,transform.position.y,newVerticalPosition);
}
}
It's working as expected.
Now, I'm following a tutorial and I copied the same as he does. But It's not working for me.
Any help please?
Thanks!
Upvotes: 0
Views: 788
Reputation: 90629
Translate
by default uses local space!
It sounds like your object (or some parent in the hierarchy) is rotated by 90°.
If you wanted global axis you should rather use
transform.Translate(movment * Time.deltaTime * speed, Space.World);
or to simplify your second snippet you can also do
transform.position += movment * Time.deltaTime * speed;
Upvotes: 1