Unity教程 移动玩家

由 小赤佬 创建, 最后一次修改 2017-11-14

编写简单的C#代码来捕捉玩家的输入并移动玩家的船。



请注意,此项目是为Unity版本4开发的。它目前正在运行,并已通过Unity版本5.1进行检查。请在观看视频时开启注释,因为当录制的内容与当前版本的Unity之间存在差异时,我们可以向视频添加注释。 


PlayerController

C#

using UnityEngine;
using System.Collections;

[System.Serializable]
public class Boundary
{
    public float xMin, xMax, zMin, zMax;
}

public class PlayerController : MonoBehaviour
{
    public float speed;
    public float tilt;
    public Boundary boundary;

    void FixedUpdate ()
    {
        float moveHorizontal = Input.GetAxis ("Horizontal");
        float moveVertical = Input.GetAxis ("Vertical");

        Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
        rigidbody.velocity = movement * speed;

        rigidbody.position = new Vector3 
        (
            Mathf.Clamp (rigidbody.position.x, boundary.xMin, boundary.xMax), 
            0.0f, 
            Mathf.Clamp (rigidbody.position.z, boundary.zMin, boundary.zMax)
        );

        rigidbody.rotation = Quaternion.Euler (0.0f, 0.0f, rigidbody.velocity.x * -tilt);
    }
}

JS

class Boundary
{
    var xMin : float;
    var xMax : float;
    var zMin : float;
    var zMax : float;
}

var speed : float;
var tilt : float;
var boundary : Boundary;

function FixedUpdate () {
     var moveHorizontal : float= Input.GetAxis ("Horizontal");
     var moveVertical : float= Input.GetAxis ("Vertical");

     var movement : Vector3= new Vector3 (moveHorizontal, 0.0f, moveVertical);
    rigidbody.velocity = movement * speed;

    rigidbody.position = new Vector3 
    (
        Mathf.Clamp (rigidbody.position.x, boundary.xMin, boundary.xMax), 
        0.0f, 
        Mathf.Clamp (rigidbody.position.z, boundary.zMin, boundary.zMax)
    );

    rigidbody.rotation = Quaternion.Euler (0.0f, 0.0f, rigidbody.velocity.x * -tilt);
}

Boo

import UnityEngine
import System.Collections

[System.Serializable]
public class Boundary:
    public xMin as single
    public xMax as single
    public zMin as single
    public zMax as single

public class PlayerController(MonoBehaviour):
    public speed as single
    public tilt as single
    public boundary as Boundary
    
    private def FixedUpdate():
        moveHorizontal as single = Input.GetAxis('Horizontal')
        moveVertical as single = Input.GetAxis('Vertical')
        
        movement = Vector3(moveHorizontal, 0.0F, moveVertical)
        rigidbody.velocity = (movement * speed)
        rigidbody.position = Vector3(Mathf.Clamp(rigidbody.position.x, boundary.xMin, boundary.xMax), 0.0F, Mathf.Clamp(rigidbody.position.z, boundary.zMin, boundary.zMax))
        rigidbody.rotation = Quaternion.Euler(0.0F, 0.0F, (rigidbody.velocity.x * (-tilt)))


W3Cschool学编程上微课-边学边练
二维码
建议反馈
二维码