- Home /
How can I rotate my player with a Joystick?
Hello, Unity community!
I got a problem with my script/Gameobject, which does not want to rotate in my Joysticks direction. The Script which I have written now just rotates the player to the cursor and not to the (virtual) Joysticks´ direction. I appreciate it, if somebody could help me, because I am pretty new to coding. Script (with the controls for android):
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityStandardAssets.CrossPlatformInput;
public class PlayerController : MonoBehaviour { public float moveSpeed; private Rigidbody myRigidbody; private Vector3 moveInput; private Vector3 moveVelocity; private Camera mainCamera;
void Start() { myRigidbody = GetComponent<Rigidbody>();
mainCamera = FindObjectOfType<Camera>(); }
void Update() {
moveInput = new Vector3(CrossPlatformInputManager.GetAxisRaw("Horizontal"), 0f, CrossPlatformInputManager.GetAxisRaw("Vertical"));
moveVelocity = moveInput * moveSpeed;
Ray cameraRay = mainCamera.ScreenPointToRay(CrossPlatformInputManager.mousePosition);
Plane groundPlane = new Plane(Vector3.up, Vector3.zero);
float rayLength; if (groundPlane.Raycast(cameraRay, out rayLength))
{
Vector3 pointToLook = cameraRay.GetPoint(rayLength);
Debug.DrawLine(cameraRay.origin, pointToLook, Color.red);
transform.LookAt(new Vector3(pointToLook.x, transform.position.y, pointToLook.z));
}
}
private void FixedUpdate() {
myRigidbody.velocity = moveVelocity;
}
}
Your answer
Follow this Question
Related Questions
How can I rotate my player with a Joystick? 0 Answers
Count time between scene executions 1 Answer
How do i get the Raycast rotation? 1 Answer
make AI shoot at incoming bullet 2 Answers
Flip over an object (smooth transition) 3 Answers