Any code to move diagonally like vector3.forward for moving forward?
Hi,
Is there any code to move diagonally like "vector3.forward" for moving forward?
if (Input.GetMouseButtonDown(0))
{
dir = Vector3.forward;
}
float amountToMove = speed * Time.deltaTime;
transform.Translate (dir * amountToMove);
}
The above makes an object move forward when clicked. What if I want to make the object move diagonally? Please help.
Answer by Dragate · Nov 08, 2017 at 07:18 AM
https://docs.unity3d.com/ScriptReference/Vector3-forward.html
As mentioned in docs, Vector3.forward corresponds to Vector3(0,0,1). If you want to move diagonally you can simply create your own Vector with different xyz values:
new Vector3(.5f,0,.5f) would move 45 degrees to the right (in the xz plane) compared to Vector3.forward.
new Vector3(-1f,0,.0) would move 90 degrees to the left(in the xz plane) compared to Vector3.forward.
However, there are also other ways to apply a rotation to your Vector3.forward, like multiplying your direction with a quaternion:
Quaternion.Euler(0, 45, 0) * Vector3.forward would move 45 degrees to the right (in the xz plane) compared to Vector3.forward.
EDIT: It is actually better to use the quaternion method if you want the rotated vector to have the same length as your original one.
oh.. I tried vector3(). Didn't know I should try new vector3. I'll try it immediately. Thanks.
Your answer
![](https://koobas.hobune.stream/wayback/20220612142544im_/https://answers.unity.com/themes/thub/images/avi.jpg)