Код: Выделить всё
using System;
using UnityEngine;
public class Movement : MonoBehaviour
{
private float _mouseSensitivity = 3f;
private float velocity = 0;
private double vangle = 0; //velocity vector angle
private float fangle = 0; //angle player is facing
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
Vector2 Avector(float angle) { //generate a vector2 with magnitude 1 pointing in the angle direction
float rad = (float)Math.PI/180;
Vector2 v = new Vector2((float)Math.Sin(angle*rad),(float)Math.Cos(angle*rad));
return v;
}
// Update is called once per frame
void Update()
{
float rad = (float)Math.PI/180;
float timeDelta = Time.deltaTime;
//decceleration by 1/sec
if (velocity < timeDelta) {
velocity = 0;
} else {
velocity -= timeDelta;
}
float z = 0;
float x = 0;
//keyboard input
if (Input.GetKey(KeyCode.W)) z += 1f;
if (Input.GetKey(KeyCode.S)) z -= 1f;
if (Input.GetKey(KeyCode.D)) x += 1f;
if (Input.GetKey(KeyCode.A)) x -= 1f;
Vector2 v = new Vector2(velocity*(float)Math.Sin(vangle*rad),velocity*(float)Math.Cos(vangle*rad));
Vector2 v1 = 4*z*Avector(fangle);//accelerate by 4/s^2
Vector2 v0 = 4*x*Avector(fangle+90);
v+=(v1+v0)*timeDelta;//update velocity vector
velocity = v.magnitude;
vangle = Math.Atan2(v.y,v.x)*180/Math.PI;
if (velocity > 8) { //cap velocity at 8
float scale = 8f/velocity;
v.x*=scale;
v.y*=scale;
velocity = 8f;
}
Vector3 move = new Vector3(v.x, 0, v.y);
transform.position+=move*timeDelta; //move player
float mouseX = Input.GetAxis("Mouse X") * _mouseSensitivity;
fangle += mouseX;
transform.localEulerAngles+=new Vector3(0,mouseX,0);
}
}
Подробнее здесь: https://stackoverflow.com/questions/792 ... t-in-unity
Мобильная версия