欢迎来到入门教程网!

C#教程

当前位置:主页 > 软件编程 > C#教程 >

Unity键盘WASD实现物体移动

来源:本站原创|时间:2020-01-10|栏目:C#教程|点击:

本文实例为大家分享了Unity键盘WASD实现物体移动的具体代码,供大家参考,具体内容如下

1首先在场景中建立一个Capsule,将主摄像机拖到其物体下。

2.将脚本挂在Capsule物体下,WASD 控制移动方向,空格延Y轴向上移动,F延Y轴向下移动

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class MoveCam : MonoBehaviour
{
 private Vector3 m_camRot;
 private Transform m_camTransform;//摄像机Transform
 private Transform m_transform;//摄像机父物体Transform
 public float m_movSpeed=10;//移动系数
 public float m_rotateSpeed=1;//旋转系数
 private void Start()
 {
  m_camTransform = Camera.main.transform;
  m_transform = GetComponent<Transform>();
 }
 private void Update()
 {
  Control();
 }
 void Control()
 {
  if (Input.GetMouseButton(0))
  {
   //获取鼠标移动距离
   float rh = Input.GetAxis("Mouse X");
   float rv = Input.GetAxis("Mouse Y");
 
   // 旋转摄像机
   m_camRot.x -= rv * m_rotateSpeed;
   m_camRot.y += rh*m_rotateSpeed;
 
  }
 
  m_camTransform.eulerAngles = m_camRot;
 
  // 使主角的面向方向与摄像机一致
  Vector3 camrot = m_camTransform.eulerAngles;
  camrot.x = 0; camrot.z = 0;
  m_transform.eulerAngles = camrot;
 
  // 定义3个值控制移动
  float xm = 0, ym = 0, zm = 0;
 
  //按键盘W向上移动
  if (Input.GetKey(KeyCode.W))
  {
   zm += m_movSpeed * Time.deltaTime;
  }
  else if (Input.GetKey(KeyCode.S))//按键盘S向下移动
  {
   zm -= m_movSpeed * Time.deltaTime;
  }
 
  if (Input.GetKey(KeyCode.A))//按键盘A向左移动
  {
   xm -= m_movSpeed * Time.deltaTime;
  }
  else if (Input.GetKey(KeyCode.D))//按键盘D向右移动
  {
   xm += m_movSpeed * Time.deltaTime;
  }
  if (Input.GetKey(KeyCode.Space) && m_transform.position.y <= 3)
  {
   ym+=m_movSpeed * Time.deltaTime;
  }
  if (Input.GetKey(KeyCode.F) && m_transform.position.y >= 1)
  {
   ym -= m_movSpeed * Time.deltaTime;
  }
  m_transform.Translate(new Vector3(xm,ym,zm),Space.Self);
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

上一篇:C#学习教程之Socket的简单使用

栏    目:C#教程

下一篇:Unity实现轮盘方式的按钮滚动效果

本文标题:Unity键盘WASD实现物体移动

本文地址:https://www.xiuzhanwang.com/a1/C_jiaocheng/4904.html

网页制作CMS教程网络编程软件编程脚本语言数据库服务器

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:835971066 | 邮箱:835971066#qq.com(#换成@)

Copyright © 2002-2020 脚本教程网 版权所有