物体移动代码示例:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PlayerController : MonoBehaviour? { ? ? float currentvelocity; ? ? public float smoothtime = 0.2f; ? ? public float walkspeed = 2f; ? ? private Animator ac; ? ? private Transform cameratransfrom; ? ? private Rigidbody rb; ? ? // Start is called before the first frame update ? ? void Start() ? ? { ? ? ? ? ac = this.GetComponent<Animator>(); ? ? ? ? cameratransfrom = Camera.main.transform; ? ? ? ? rb = this.GetComponent<Rigidbody>(); ? ? }
? ? // Update is called once per frame ? ? void Update() ? ? { ? ? ? ? Vector2 input = new Vector2(Input.GetAxisRaw("Horizontal"),Input.GetAxisRaw("Vertical")); ? ? ? ? Vector2 inputdir = input.normalized; ? ? ? ? float targetrotation = Mathf.Atan2(inputdir.x, inputdir.y) * Mathf.Rad2Deg+cameratransfrom.eulerAngles.y; ? ? ? ? //判断是否为0? ? ? ? ? if (inputdir!=Vector2.zero) ? ? ? ? { ? ? ? ? ? ? transform.eulerAngles = Vector3.up * Mathf.SmoothDampAngle(transform.eulerAngles.y, targetrotation, ref currentvelocity, smoothtime); ? ? ? ? ? ? transform.Translate(transform.forward*walkspeed*Time.deltaTime,Space.World); ? ? ? ? ? ? rb.MovePosition(transform.position + transform.forward * Time.deltaTime * walkspeed); ? ? ? ? ? ? ac.SetBool("Move?",true); ? ? ? ? } ? ? ? ? else ? ? ? ? { ? ? ? ? ? ? ac.SetBool("Move?",false); ? ? ? ? } ? ? } }
?
|