第一个脚本实现效果:鼠标单机移动物体
基础部分终于看的差不多了。
要开始写代码,实现效果了~
程序基础不怎么好,慢慢来~~
点击鼠标左键 物体移动到鼠标位置
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);
}
}