unity3d中最简单物体的旋转移动
void Awake (){
}
//初始化函数,在游戏开始时系统自动调用。一般用来创建变量之类的东西。
void Start(){
}
//初始化函数,在所有Awake函数运行完之后(一般是这样,但不一定),在所有Update函数前系统自动条用。一般用来给变量赋值。
我们通常书写的脚本,并不会定义[ExecuteInEditMode]这个Attribute,所以Awake和Start都只有在Runtime中才会执行。
using UnityEngine;
using System.Collections;
public class square1 : MonoBehaviour {
public float m_speed = 1;
protected Transform m_transform;
//是否被拖拽
private bool
onDrag=false;
//旋转速度
public float speed=6f;
//阻尼速度
private
float tempSpeed;
//水平
private float axisX;
//竖直
private
float axisY;
//鼠标移动的距离
private float cXY;
// Use this for initialization
void Start () {
//调用
m_transform = this.transform;
}
// Update is called
once per frame
void Update () {
float movev = 0;
float moveh = 0;
if
(Input.GetKey(KeyCode.UpArrow))
{
movev += m_speed *
Time.deltaTime;
}
if (Input.GetKey(KeyCode.DownArrow))
{
movev -= m_speed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.RightArrow))
{
moveh += m_speed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.LeftArrow))
{
moveh -= m_speed * Time.deltaTime;
}
gameObject.transform.Rotate(new
Vector3(axisX,axisY,0)*Rigid(),Space.World);
if
(!Input.GetMouseButton(0))
{
onDrag = false;
}
transform.Translate(Vector3.forward*Time.captureFramerate);
this.m_transform.Translate(new Vector3(moveh, 0, movev));
}
//接受鼠标按下
void OnMouseDown()
{
axisX = 0f;
axisY
= 0f;
}
//鼠标拖拽时的操作
void OnMouseDrag()
{
onDrag = true;
axisX = -Input.GetAxis("Mouse X");
axisY = Input.GetAxis("Mouse
Y");
cXY = Mathf.Sqrt(axisX*axisX+axisY*axisY);
if
(cXY==0f)
{
cXY = 1f;
}
}
//计算阻尼
float Rigid()
{
if (onDrag)
{
tempSpeed = speed;
}
else
{
if (tempSpeed>0)
{
tempSpeed -= speed * 2 *
Time.deltaTime / cXY;
}
else
{
tempSpeed = 0;
}
}
return
tempSpeed;
}
//实现鼠标的拖拽移动
IEnumerator OnMouse()
{
var camear = Camera.mainCamera;
if (camear)
{
Vector3 screenPosition =
camear.WorldToScreenPoint(transform.position);
Vector3
mscreenPosition = new
Vector3(Input.mousePosition.x,Input.mousePosition.y,screenPosition.z);
Vector3 offset = transform.position -
camear.ScreenToWorldPoint(mscreenPosition);
print("drag
strating:"+transform.name);
while (Input.GetMouseButton(0))
{
mscreenPosition = new
Vector3(Input.mousePosition.x,Input.mousePosition.y,screenPosition.z);
transform.position = offset +
camear.ScreenToWorldPoint(mscreenPosition);
yield return new
WaitForEndOfFrame();
}
print("drag
compeleted");
}
}
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。