- Home /
Question by
cliffmlimwa · Apr 08, 2020 at 03:15 PM ·
camerarotationjoystick
move the object where camera look
i have script move the player with joystic the problem is when i rotate the camera the player not move to y axis when camera facing y
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Motor : MonoBehaviour
{
public float moveSpeed = 5.0f;
public float drag = 5.0f;
public float terminalRotationSpeed = 25.0f;
public VirtualJoystick moveJoystick;
private Rigidbody rgb;
private Transform camTras;
Vector3 dir;
private void Awake()
{
camTras = Camera.main.transform;
}
// Use this for initialization
private void Start()
{
rgb = GetComponent<Rigidbody>();
rgb.maxAngularVelocity = terminalRotationSpeed;
rgb.drag = drag;
}
// Update is called once per frame
private void Update()
{
dir = Vector3.zero;
dir.x = Input.GetAxis("Horizontal");
dir.z = Input.GetAxis("Vertical");
if (dir.magnitude > 1)
dir.Normalize();
if (moveJoystick.InputDirection != Vector3.zero)
{
dir = moveJoystick.InputDirection;
// transform.forward = Camera.main.transform.forward;
}
//Rotate direction vector with camera
Vector3 rotatedDir = camTras.TransformDirection(dir);
rotatedDir = new Vector3(rotatedDir.x, 0, rotatedDir.z);
rotatedDir = rotatedDir.normalized * dir.magnitude;
rgb.AddForce(dir * moveSpeed);
}
}
i got suggestion in stack over i can put below code into update but when i put that the player not move anymore help please
private void Update ()
{
Vector3 dir = Vector3.zero;
dir.x = Input.GetAxis ("Horizontal");
dir.z = Input.GetAxis ("Vertical");
if (dir.magnitude > 1)
dir.Normalize ();
if (movejoystick.InputDirection != Vector3.zero) {
dir = movejoystick.InputDirection;
}
Vector3 rotatedDir = transform.TransformDirection (dir); // world direction of joystick direction
Vector3 newDir = Vector3.RotateTowards(transform.forward, rotatedDir, Time.deltaTime * 10f, 0.0F); // turn towards joystick direction
transform.rotation = Quaternion.LookRotation(newDir); // set the new direction
controller.AddForce (transform.forward * moveSpeed * dir.z); // scale force by joystick up/down
}
Comment
Your answer
Follow this Question
Related Questions
How to deal with joystick moving and screen swiping colliding? 0 Answers
How do I properly rotate an FPS camera with a joystick? 1 Answer
Joystick problem (i only want horizontal movement) 0 Answers
Joystick controls - camera rotating problem 2 Answers
advanced problem for me regarding transfering rotation from the gizmo to the object 0 Answers