首页 > 解决方案 > 我怎样才能继续触摸“Kinematic”Rigidbody2D?

问题描述

所以有我的角色的 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));

    }
}

标签: c#androidunity3d

解决方案


来自Unity 文档

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

因此,与其施加力,不如改变它的位置。像这样的东西:

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

}

推荐阅读