点击鼠标右键,角色随之移动到右键位置
using UnityEngine;
using System.Collections;
public class Move : MonoBehaviour {
private bool finish = true ;
private Vector3 pos;
void Start () {
}
void Update () {
if (Input.GetMouseButtonDown(1 ))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit = new RaycastHit();
if (Physics.Raycast(ray,out hit))
{
if (hit.collider.tag=="TT" )
{
pos = hit.point;
finish = false ;
}
}
}
if (!finish)
{
Vector3 offset = pos - transform.position;
transform.position += offset.normalized * 20 * Time.deltaTime;
if (Vector3.Distance(pos,transform.position)<1 f)
{
transform.position = pos;
finish = true ;
}
}
}
}
第二种小方法
这种方法有点小复杂,实用性比较好,下面是简单代码
using UnityEngine;
using System.Collections;
public class Move_1 : MonoBehaviour {
public float speed = 5 f;
private PlayDir dir;
private CubeCS cubeCS;
private void Awake ()
{
dir = this .GetComponent<PlayDir>();
cubeCS = this .GetComponent<CubeCS>();
}
void Start () {
}
void Update () {
}
private void FixedUpdate ()
{
float distance = Vector3.Distance(dir.targetPosition, transform.position);
if (distance>0.1 f)
{
cubeCS.rb.velocity = transform.forward * speed * distance;
}else
{
cubeCS.rb.velocity = transform.forward * 0 ;
}
}
}
-------------------------------
using UnityEngine;
using System.Collections;
public class CubeCS : MonoBehaviour {
public Rigidbody rb;
public float speed = 5 ;
public float angularSpeed = 3 ;
private void Awake ()
{
rb = this .GetComponent<Rigidbody>();
}
void Start () {
}
void Update () {
}
private void FixedUpdate ()
{
Move();
}
private void Move ()
{
float v = Input.GetAxis("Vertical" );
rb.velocity = this .transform.forward * v * speed;
float h = Input.GetAxis("Horizontal" );
rb.angularVelocity = this .transform.up * h * angularSpeed;
}
}
-----------------------------------
using UnityEngine;
using System.Collections;
public class PlayDir : MonoBehaviour {
private bool isMoving = false ;
public Vector3 targetPosition;
private void Awake ()
{
targetPosition = this .transform.position;
}
void Start () {
}
void Update () {