1. 程式人生 > >Unity 2D角色移動

Unity 2D角色移動

 

 

移動方式一(Rigidbody2D

  適用說明:

  1,使用Rigidbody2D方式的移動,結束移動後會有一些移動慣性;

  2,可以在Rigidbody2D剛體元件中設定線性阻尼,來抵消這種移動慣性,設值越大慣性越小;

  3,為角色新增Rigidbody2D元件,剛體元件;

  程式碼示例:

  

 1 using System.Collections;
 2 using System.Collections.Generic;
 3 using UnityEngine;
 4 
 5 public class Move : MonoBehaviour {
6 7 8 private Rigidbody2D m_Rigidbody2D; 9 10 private float moveSpeed = 5.0f; 11 12 void Start () { 13 14 m_Rigidbody2D = gameObject.GetComponent<Rigidbody2D>(); 15 16 } 17 18 19 void FixedUpdate() { 20 21 float H = Input.GetAxis("Horizontal
"); 22 float V = Input.GetAxis("Vertical"); 23 24 Vector2 playerMove = new Vector2(H,V); 25 26 m_Rigidbody2D.AddForce(playerMove*moveSpeed); 27 28 29 } 30 }