I want to move my Player (a sphere) with WASD and if i press W it should move towards the direction where the camera is looking and so on.
Here’s my Script for the Player:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.SceneManagement;
public class PlayerController : MonoBehaviour
{
public float speed;
public float jumpHight;
private Rigidbody rby;
void Start()
{
rby = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
float moveVertical = Input.GetAxis("Vertical");
float moveHorizontal = Input.GetAxis("Horizontal");
Vector3 movement = new Vector3(moveVertical, 0.0f, moveHorizontal);
rby.AddForce(movement * speed);
if (Input.GetButtonDown("Jump"))
{
GetComponent<Rigidbody>().velocity = Vector3.up * jumpHight;
}
if (Input.GetKeyDown(KeyCode.Tab))
{
SceneManager.LoadSceneAsync(SceneManager.GetActiveScene().name);
}
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Pick Up"))
{
other.gameObject.SetActive(false);
}
}
}
And here is my Camera Controller Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraController : MonoBehaviour {
private const float Y_ANGLE_MIN = 0.0f;
private const float Y_ANGLE_MAX = 50.0f;
public Transform lookAt;
public Transform camTransform;
private Camera cam;
private float distance = 10.0f;
private float currentX = 0.0f;
private float currentY = 0.0f;
private float sensivityX = 4.0f;
private float sensivityY = 1.0f;
private void Start()
{
camTransform = transform;
cam = Camera.main;
}
private void Update()
{
currentX += Input.GetAxis("Mouse X") * sensivityX;
currentY += Input.GetAxis("Mouse Y") * sensivityY;
currentY = Mathf.Clamp(currentY, Y_ANGLE_MIN, Y_ANGLE_MAX);
}
private void LateUpdate()
{
Vector3 dir = new Vector3(0, 0, -distance);
Quaternion rotation = Quaternion.Euler(currentY, currentX, 0);
camTransform.position = lookAt.position + rotation * dir;
camTransform.LookAt(lookAt.position);
}
}
And sry for my bad English D: