第一个脚本实现效果:鼠标单机移动物体
基础部分终于看的差不多了。
要开始写代码,实现效果了~
程序基础不怎么好,慢慢来~~
点击鼠标左键 物体移动到鼠标位置
C#实现
using UnityEngine;
using System.Collections;
public class Script_01 : MonoBehaviour
{
private Vector3 world;
private float speed; //the move speed of object
void Start ()
{
}
void Update ()
{
Vector3 screenpos=Camera.main.WorldToScreenPoint(transform.position); //turn the coordinate of object from World to Screen
Vector3 m=Input.mousePosition; //the position of mouse
//when mouse click
if(Input.GetMouseButton(0))
{
m.z=screenpos.z; //give a z axis coordinate to mouse
world=Camera.main.ScreenToWorldPoint(m); //change to world coordinate
speed=30;
}
if(transform.position==world)
{
speed=0;
}
transform.LookAt(world); //let the object look at mouse
transform.Translate(Vector3.forward*speed*Time.deltaTime);
}
}
基础部分终于看的差不多了。
要开始写代码,实现效果了~
程序基础不怎么好,慢慢来~~
点击鼠标左键 物体移动到鼠标位置
C#实现
using UnityEngine;
using System.Collections;
public class Script_01 : MonoBehaviour
{
private Vector3 world;
private float speed; //the move speed of object
void Start ()
{
}
void Update ()
{
Vector3 screenpos=Camera.main.WorldToScreenPoint(transform.position); //turn the coordinate of object from World to Screen
Vector3 m=Input.mousePosition; //the position of mouse
//when mouse click
if(Input.GetMouseButton(0))
{
m.z=screenpos.z; //give a z axis coordinate to mouse
world=Camera.main.ScreenToWorldPoint(m); //change to world coordinate
speed=30;
}
if(transform.position==world)
{
speed=0;
}
transform.LookAt(world); //let the object look at mouse
transform.Translate(Vector3.forward*speed*Time.deltaTime);
}
}
本文介绍了一个简单的Unity脚本,该脚本使用C#语言使物体能够在鼠标左键点击时移动到鼠标的位置。通过转换坐标系并利用速度控制物体平滑地移动到目标位置。
2394

被折叠的 条评论
为什么被折叠?



