- Home /
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 THIS LINK 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
Are you trying to move up the character when the camera facing y?
can you help me to modify my code so player can move to camera direction i'm trying a lot and fail
Your answer
Follow this Question
Related Questions
Flip over an object (smooth transition) 3 Answers
move the object where camera look 0 Answers
Character goes up when the camera looks up 0 Answers
Move towards VR Camera Orientation with Bluetooth Controller (Android) 0 Answers
Rotate player to screen pos 0 Answers