简体   繁体   中英

How can i make to move on touch “Kinematic” Rigidbody2D?

So there is the code with my Character's Rigidbody2D attachment, but he does not move when is set to Kinematic (working only on Dynamic), but I want Kinematic because he collides with Dynamic Objects and i didn't want him to move just left and right on touch.

UI: I'm very beginner, I just want to make my first game for Android and sorry for my english too. :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));

    }
}

From Unity docs ,

If isKinematic is enabled, Forces, collisions or joints will not affect the rigidbody anymore.

So instead of applying a force, just change it's position. Something like this:

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM