unity 控制玩家物体

创建场景

放上一个plane,放上一个球 sphere,假定我们的球就是我们的玩家,使用控制键w a s d 来控制球也就是玩家移动。增加一个材质,把颜色改成绿色,把材质赋给plane,区分我们增加的白球。
unity 控制玩家物体_第1张图片

增加组件和脚本

增加一个Character Controller 组件,同时给圆球增加一个脚本control。
unity 控制玩家物体_第2张图片

增加c# 脚本

脚本如下所示:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class playercontrol : MonoBehaviour
{
    // Start is called before the first frame update
    private CharacterController player;
    void Start()
    {
        player = GetComponent<CharacterController>();
    }

    // Update is called once per frame
    void Update()
    {
        float horizontal = Input.GetAxis("Horizontal");
        float vertical = Input.GetAxis("Vertical");
        Vector3 direction = new Vector3 (horizontal,0, vertical);
        player.SimpleMove(direction);
    }
}

运行测试

点击运行 按下 wasd 键盘,圆球会按照我们的键移动,同时按下wd 键时,会斜轴走动,读者可以自信测试。使用character control 会使得移动更为简单,如果我们需要其他的移动方式,对一些场景中的物体进行移动,也可以使用transform,如下为测试代码,注意脚本挂载到哪个物体上
unity 控制玩家物体_第3张图片

如上图所示,再增加一个立方体,写一个脚本move.cs,挂载到立方体上,脚本如下所示

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class move : MonoBehaviour
{
    // Start is called before the first frame update
    [SerializeField] private float moveSpeed = 10.1f;
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.W))
        {
            //transform.position +
            //transform.position -
            Vector3 pos = Vector3.up * moveSpeed * Time.deltaTime;
            Debug.Log(Time.deltaTime);
            Debug.Log(pos);
            transform.Translate(Vector3.up * moveSpeed * 0.1f);
        }
        else if (Input.GetKeyDown(KeyCode.S))
        {
            transform.Translate(Vector3.down * moveSpeed * 0.1f);
        }
        else if (Input.GetKeyDown(KeyCode.Z))
        {
            transform.position = Vector3.MoveTowards(transform.position, new Vector3(0, 0, 0), moveSpeed);
        }
    }
}

运行测试

这样再按键wasd 时,两个物体都会移动,不同的是,立方体是上下移动。当然同时移动可能逻辑上不对,读者可以自行修改,点中哪一个再移动哪一个。

你可能感兴趣的:(unity,c#,unity,游戏引擎)