雷火电竞-中国电竞赛事及体育赛事平台

歡迎來到入門教程網(wǎng)!

C#教程

當前位置:主頁 > 軟件編程 > C#教程 >

Unity鍵盤WASD實現(xiàn)物體移動

來源:本站原創(chuàng)|時間:2020-01-10|欄目:C#教程|點擊:

本文實例為大家分享了Unity鍵盤WASD實現(xiàn)物體移動的具體代碼,供大家參考,具體內(nèi)容如下

1首先在場景中建立一個Capsule,將主攝像機拖到其物體下。

2.將腳本掛在Capsule物體下,WASD 控制移動方向,空格延Y軸向上移動,F(xiàn)延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;//移動系數(shù)
 public float m_rotateSpeed=1;//旋轉(zhuǎn)系數(shù)
 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");
 
   // 旋轉(zhuǎn)攝像機
   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);
 }
}

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持我們。

上一篇:C#學習教程之Socket的簡單使用

欄    目:C#教程

下一篇:Unity實現(xiàn)輪盤方式的按鈕滾動效果

本文標題:Unity鍵盤WASD實現(xiàn)物體移動

本文地址:http://www.jygsgssxh.com/a1/C_jiaocheng/4904.html

網(wǎng)頁制作CMS教程網(wǎng)絡編程軟件編程腳本語言數(shù)據(jù)庫服務器

如果侵犯了您的權(quán)利,請與我們聯(lián)系,我們將在24小時內(nèi)進行處理、任何非本站因素導致的法律后果,本站均不負任何責任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有