Z
Z
ZeynGort2020-07-01 16:08:47
Unity
ZeynGort, 2020-07-01 16:08:47

Unity 2d function Collider 2D why not working?

Hello, I recently started studying Unity, because I thought that I wanted to not only play, but also create something of my own, and a day later I ran into something I don’t understand. I created two objects and gave them a Collider 2D component, since one of the objects is a hero, I also gave him a Rigidbody 2D and a key movement script. (The hero's Body Type is Kinematic). When I started to check the character, to my joy, it moved quite well, only it passed through the object through the place where it would hit it.
Help!
Here is the script for movement, maybe there is an error in it.

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

public class control : MonoBehavior
{
public float speed;
private Rigidbody2D rb;
private Vector2 moveVelocity;

void Start()
{
rb = GetComponent<Rigidbody2D>();
}


void Update()
{
Vector2 moveInput = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
moveVelocity = moveInput. normalized * speed;

}
void FixedUpdate()
{
rb.MovePosition(rb.position + moveVelocity * Time.fixedDeltaTime);
}
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Pavlov, 2020-07-02
@ZeynGort

>The hero's Body Type is Kinematic
The hero's Body Type must be Dynamic, otherwise the physics won't work. Type Kinematic - the position of the object is completely controlled by the script, not by physics. So, if you want to use physics, then use the Dynamic type.
Obstacles can be made kinematic or even static (for example, the ground or fixed platforms), then they will not move by the character (kinematic ones can be moved by the script), and if you want to throw rocks or boxes (using physics), then they must also be dynamic. Plus, for dynamic objects, you need to specify the correct mass.
To begin with, I recommend a series of three articles (in the second, see the comment for finalizing the old code in new versions of the unit)

H
Herman Coffman, 2020-07-01
@Gera01

rb = GetComponent();It doesn't work like that, because you have a lot of components on the object, so you need to specify the type. rb = GetComponent<Rigidbody2D >();
And for the function to work, OnCollisionEnter2Dyou need to write it ...
That is:

private void OnCollisionEnter2D(Collision2D collision)
    {
        //и тут ты описываешь что тебе нужно сделать при столкновении. 
    }

And next time, check everything yourself, and then ask a question)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question