在这个例子中,通过键盘的左右方向来控制场景中的球体 Sphere 的横向运动,而 Cube 立方体则会一直朝着球体旋转。
1.在场景中新建一个 Cube 立方体和一个 Sphere 球体,在 Inspector 视图中设置 Cube 立方体的坐标为(3,0,4),Sphere 球体坐标为(0,0,0)。
2.新建 C# 脚本 MotionControl,并将其附给 Sphere 球体对象
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class MotionControl : MonoBehaviour
{public float speed = 3f; //定义一个速度// Start is called before the first frame updatevoid Start(){}// Update is called once per framevoid Update(){//控制物体移动transform.Translate(-Input.GetAxis("Horizontal") * speed * Time.deltaTime,0 ,0);}
}
3.新建 C# 脚本 LookAtControl,并将其附给 Cube 立方体对象
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class LookAtControl : MonoBehaviour
{public Transform target; //定义的朝向目标// Start is called before the first frame updatevoid Start(){//查找场景中名为 " " 的对象,赋值给targettarget = GameObject.Find("Sphere").transform;}// Update is called once per framevoid Update(){//计算该脚本物体指向 target 的向量Vector3 relativePos = target.position - transform.position;//该脚本物理一直朝着 target 目标transform.rotation = Quaternion.LookRotation(relativePos);}
}
4.点击播放按钮,通过键盘左右方向键(或者A,D键)控制球体运动,而 Cube 立方体会一直朝向 Sphere 球体。