我的动作脚本出了什么问题?

时间:2017-04-20 21:54:43

标签: c# unity3d unity5

所以我对整个团结的事情有点新意。我已经在C#中编程了一段时间,通常是为了移动一些东西我只是做了一点“_playerPosition.x + = 5;”但是我在Unity中尝试过它并没有起作用。 这是我目前的行动代码:

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

public class PlayerMovement : MonoBehaviour {
Vector2 _playerPosition;
GameObject Player;
// Use this for initialization
void Start () {
    _playerPosition = Vector2.zero;
}

// Update is called once per frame
void Update () {
    if (Input.GetKey(KeyCode.W)) {
        _playerPosition.y += 5f; 
    }

    if (Input.GetKey(KeyCode.S)) {
        _playerPosition.y -= 5f;
    }

    if (Input.GetKey(KeyCode.D)) {
        _playerPosition.x += 5f;
    }
    if (Input.GetKey(KeyCode.A)) {
        _playerPosition.x -= 5f;
    }
    Player.transform.position = _playerPosition;
}

}

3 个答案:

答案 0 :(得分:1)

您应该只是移动脚本附加的播放器

public float speed = 5f;

void Update()
{
    if (Input.GetKey(KeyCode.W))
    {
        transform.position += Vector3.up * speed * Time.deltaTime;
    }

    if (Input.GetKey(KeyCode.S))
    {
       transform.position += Vector3.down * speed * Time.deltaTime;
    }

    if (Input.GetKey(KeyCode.D))
    {
        transform.position += Vector3.right * speed * Time.deltaTime;
    }
    if (Input.GetKey(KeyCode.A))
    {
        transform.position += Vector3.left * speed * Time.deltaTime;
    }
}

Similar question on Unity

您可以根据自己的喜好更改speed的值。

答案 1 :(得分:0)

_playerPosition是一个包含Vector2的变量,正如您在评论中提到的那样。确保在所有计算后使用该变量设置新位置。

修改

检查出来。请记住将Player对象从场景分配到脚本中。

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

public class PlayerMovement : MonoBehaviour {
    Vector2 _playerPosition;
    public GameObject Player; // assign your player prefab

    void Start () {
        _playerPosition = Vector2.zero;
    }

    void Update () {
        if (Input.GetKey(KeyCode.W)) {
            _playerPosition.y += 5f; 
        }

        if (Input.GetKey(KeyCode.S)) {
            _playerPosition.y -= 5f;
        }

        if (Input.GetKey(KeyCode.D)) {
            _playerPosition.x += 5f;
        }
        if (Input.GetKey(KeyCode.A)) {
            _playerPosition.x -= 5f;
        }

        Player.transform.position = _playerPosition;
    }

}

答案 2 :(得分:0)

在更新中尝试此操作

void Update(){
    int d = 0;
    int speed = 5;
    if (Input.GetKeyDown(KeyCode.W)) {
       d=90; 
    }
    if (Input.GetKeyDown(KeyCode.S)) {
        d = 270;
    }
    if (Input.GetKeyDown(KeyCode.D)) {
        d = 0;
    }
    if (Input.GetKeyDown(KeyCode.A)) {
        d=180;
    }
    this.transform.position += new Vector3((int)(speed * Mathf.Sin(d * Mathf.Deg2Rad)), 0, (int)(speed * Mathf.Cos(d * Mathf.Deg2Rad)));
}

相反,这是一个3d,但可以转移到2d