如何使"Kinematic" Rigidbody2D 在触摸时移动?

4

这是我的角色 Rigidbody2D 代码,但当它设置为 Kinematic 时,他不会移动(仅在 Dynamic 上工作),但我想要 Kinematic 因为他与动态对象碰撞,并且我不希望他只是在触摸左右移动。

UI:我是个新手,我只想制作我的第一个 Android 游戏,对我的英语也很抱歉。 :D

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

public class Movement : MonoBehaviour
{
    //variables
    public float moveSpeed = 300;
    public GameObject character;

    private Rigidbody2D characterBody;
    private float ScreenWidth;


    // Use this for initialization
    void Start()
    {
        ScreenWidth = Screen.width;
        characterBody = character.GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        int i = 0;
        //loop over every touch found
        while (i < Input.touchCount)
        {
            if (Input.GetTouch(i).position.x > ScreenWidth / 2)
            {
                //move right
                RunCharacter(1.0f);
            }
            if (Input.GetTouch(i).position.x < ScreenWidth / 2)
            {
                //move left
                RunCharacter(-1.0f);
            }
            ++i;
        }
    }
    void FixedUpdate()
    {
#if UNITY_EDITOR
        RunCharacter(Input.GetAxis("Horizontal"));
#endif
    }

    private void RunCharacter(float horizontalInput)
    {
        //move player
        characterBody.AddForce(new Vector2(horizontalInput * moveSpeed * Time.deltaTime, 0));

    }
}
1个回答

0

来自Unity文档,

如果启用了isKinematic,力、碰撞或关节将不再影响刚体。

因此,不要施加力,只需改变其位置。像这样:

private void RunCharacter(float horizontalInput)
{
    //move player
    characterBody.transform.position += new Vector2(horizontalInput * moveSpeed * Time.deltaTime, 0);

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接