Vector3 newPosition = new Vector3(-horizontal, 0.0f, -vertical);
transform.LookAt(newPosition + transform.position);
transform.Translate(newPosition * MoveSpeed * Time.deltaTime, Space.World);
I'm developing 3d mobile game, you can look around with hold&sliding the right side of the screen and move with virtual joystick.
Goal;
Moving character to camera's lookDirection
Issue is;
When i push joystick up, character moves to the same direction (world related)
And I'm not good at coding that's why i can't solve the problem myself, i would be glad if you help me
Answer
Here's how I calculated my movement according to my camera's direction:
Note: There's TouchField because my game is for mobile. If your game is not mobile you need to calculate somethings different than mine.
void Movement()
{
Vector2 vec = new Vector2(horizontal, vertical);
vec = Vector2.ClampMagnitude(vec, 1f);
Vector3 camF = cam.transform.forward;
Vector3 camR = cam.transform.right;
Vector3 rbVelocity = rb.velocity;
camF.y = 0;
camR.y = 0;
rbVelocity.y = 0;
camF = camF.normalized;
camR = camR.normalized;
targetPosition = (camF * vec.y + camR * vec.x) * MoveSpeed;
Vector2 targetVelocity = (targetPosition - transform.position)/Time.deltaTime;
rb.AddForce(targetPosition - rbVelocity, ForceMode.VelocityChange);
transform.eulerAngles = new Vector3(transform.eulerAngles.x, transform.eulerAngles.y, Mathf.Clamp(transform.eulerAngles.z, 0, 0));
Vector3 deltaPosition = transform.position - prevPosition;
if (deltaPosition.sqrMagnitude > 0.1 * Time.deltaTime * Time.deltaTime)
{
transform.forward = deltaPosition;
}
prevPosition = transform.position;
CameraAngle += FixedTouchField.TouchDist.x * CameraAngleSpeed;
Camera.main.transform.rotation = Quaternion.LookRotation(transform.position + Vector3.up * 2f - Camera.main.transform.position, Vector3.up);
}
No comments:
Post a Comment