[Resolved] Translate an object on a angle along Y and Z axis (c#)

Hi

I’m trying to move an object along a fixed angle which travels in both the Y and Z axis, moving towards the camera. I’m very foggy when it comes this kind of maths so I’ve no doubt messed it up completely. The code below is what I’ve been playing with trying to get it to work but no luck - I’ve no doubt gone about this all the wrong way so I was hoping someone could help me out.

public class ObjectControl : MonoBehaviour {
	
	float speed;
	float angleDeg = 315.0f;
	float angleRad;
	
	void Start () 
	{
		angleRad = angleDeg * (Mathf.PI / 180);
	}
	
	void Update () 
	{
		speed = Time.deltaTime * 8;
		
		if(Input.GetKey(KeyCode.Space))
		{
			transform.Translate(0, speed * Mathf.Cos(angleRad), speed * Mathf.Sin(angleRad)); 
		}
	}
}

Thanks in advance

Transform.translate assumes the input is in your local coords, so if the object isn’t pointing due North (blue Z axis) than it moves funny. Then, Mathf uses the “real” cos/sin: 0 degrees is East, and rotates CCW. So 315 degrees (as radians, like you have) is -45 degrees, is SouthEast. Then normally Cos is x and Sin is y, which would work if you had a sideways-facing camera (facing along x, so it sees y and z) rotated 90 degrees (so +y is right.)

Unity has a number of things to simplify moving, and most people (even people who know the math well) just use those. For example, moving forwards to the target:

Vector3 targPos; // set somehow
transform.LookAt(targPos);

transform.Translate(Vector3.forward * speed);
// moves my forward, which is where I'm looking, which is the target

Or the same idea but not spinning to face:

transform.position = Vector3.MoveTowards(transform.position, targPos, speed);

Or using Quaternions to get the angle (these are less understood, but are standard in 3D motion):

Quaternion moveAng = Quaternion.Euler(315,0,0);
// angles are in degrees, 000 is due north, Clockwise, left-handed.
// 315 around x is North and up 45.

transform.position += moveAng*(Vector3.forward*speed);