unity3D中使用鼠标控制物体移动的方法

using UnityEngine;
using System.Collections;
//获得目标位置的代码
public class Target : MonoBehaviour {
    public Transform targetMatker;

    void Start() { }

    void Update()
    {
        int button = 0;

        if (Input.GetMouseButtonDown(button))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hitInfo;
<span style="white-space:pre">		</span>//移动到鼠标指定的位置后停止
            if (Physics.Raycast(ray.origin, ray.direction, out hitInfo))
            {
                Vector3 targetPosition = hitInfo.point;
                targetMatker.position = targetPosition;
            }
        }
    }
}




using UnityEngine;
using System.Collections;

//要控制移动的物体的代码
public class PlayerTank : MonoBehaviour {
    public Transform targetTransform;
    private float movementSpeed, rotSpeed;


    void Start()
    {
        movementSpeed = 10.0f;
        rotSpeed = 2.0f;
    }


    void Update()
    {
        //接近要到达的目标指定位置后就停止
        if (Vector3.Distance(transform.position, targetTransform.position) < 5.0f)
            return;
        //实时计算要到达的目标位置与当前位置的距离
        Vector3 tarPos = targetTransform.position;
        tarPos.y = this.transform.position.y;
        Vector3 dirRot = tarPos - transform.position;
        //创建一个四元数指向当前位置与目标位置的角度
        Quaternion tarRot = Quaternion.LookRotation(dirRot);
        //当旋转和移动的时候插入一个值
        transform.rotation = Quaternion.Slerp(transform.rotation, tarRot, rotSpeed * Time.deltaTime);


        transform.Translate(new Vector3(0, 0, movementSpeed * Time.deltaTime));
        
    }


  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值