• 主页

  • 投资

  • IT

    🔥
  • 设计

  • 销售

  • 共151篇

    Unity - 游戏引擎

关闭

返回栏目

关闭

返回Unity - 游戏引擎栏目

38 - C# - 单机双人移动wasd、上下左右

作者:

贺及楼

成为作者

更新日期:2024-05-10 16:25:46

作用:wasd、上下左右

代码:

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class tankmovement : MonoBehaviour
  5. {
  6. public float speed = 5;
  7. private Rigidbody rigidbody;
  8. public float angularspeed = 7;
  9. public float number = 1;
  10. // Start is called before the first frame update
  11. void Start()
  12. {
  13. rigidbody = this.GetComponent<Rigidbody>();
  14. }
  15. // Update is called once per frame
  16. void Update()
  17. {
  18. float v = Input.GetAxis("VerticalPlayer"+ number);
  19. rigidbody.velocity = transform.forward * v * speed;
  20. float h = Input.GetAxis("HorizontalPlayer" + number);
  21. rigidbody.angularVelocity = transform.up * h * angularspeed;
  22. }
  23. }

代码的翻译:

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class tankmovement : MonoBehaviour
  5. {
  6. public float speed = 5;//前进速度
  7. private Rigidbody rigidbody;
  8. public float angularspeed = 7;//转弯速度
  9. public float number = 1;//玩家编号
  10. // Start is called before the first frame update
  11. void Start()
  12. {
  13. rigidbody = this.GetComponent<Rigidbody>();
  14. }
  15. // Update is called once per frame
  16. void Update()
  17. {
  18. float v = Input.GetAxis("VerticalPlayer"+ number);//玩家编号+ws
  19. rigidbody.velocity = transform.forward * v * speed;
  20. float h = Input.GetAxis("HorizontalPlayer" + number);//玩家编号+ad
  21. rigidbody.angularVelocity = transform.up * h * angularspeed;//角度
  22. }
  23. }

用法:

1、Rigibody - freeze Position:锁y轴
2、Rigibody - freeze Rotation:锁x、z轴
3、Eidt - Project Setting - Input - Horizontal -右键复制Duplicate Array Element2次 - 命名HorizontalPlayer1、HorizontalPlayer2
4、Eidt - Project Setting - Input - Vertical -右键复制Duplicate Array Element2次 - VerticalPlayer1、VerticalPlayer2
5、Player1 - 使用wasd - 删掉上下左右键
6、Player2 - 使用上下左右键 - 删掉wasd