I have a very strange problem in my 2D Unity game, which I was able to reduce to the next main problem / minimal test case reproduction. Follow these steps to play (Unity 5.1.1f1):
- Create a player object (cube) in place
(0,0,0). - Remove the component
BoxCollider. - Attach the following
C#script, Unity will automatically add the necessary components and thereby make it a Rigidbody Collider. - Set the flag
isKinematic. - Add another cube to the scene in place
(2,0,0). - Remove the component
BoxColliderand add BoxCollider2D. This makes this cube a static collider. - Set the flag
isTrigger. - Run the scene.
Expected Behavior:
A player’s cube accelerates to another cube and stops when it touches it.
Observed behavior:
The player’s cube accelerates to another cube and then continues to move at a constant speed.
:
, Rigidbodies , . , . - , rigidbody.MovePosition(), transform.Translate() transform.position. script, .
transform.position , , , , , .
:
Update() Time.deltaTime .Update() timestep 0, stop. .- , , , . - Rigidbody ( ) . , 0.
velocity 0, . , Update() ( , Debug.Log() ).
, , 30 , , . , , , . .
SimpleController2D.cs
using UnityEngine;
using System.Collections;
[RequireComponent (typeof (BoxCollider2D), typeof (Rigidbody2D))]
public class SimpleController2D : MonoBehaviour {
public Vector3 velocity = Vector3.zero;
private Transform thisTransform;
private Rigidbody2D thisRigidbody;
public bool stop = false;
void Awake () {
thisTransform = GetComponent<Transform> ();
thisRigidbody = GetComponent<Rigidbody2D> ();
}
void FixedUpdate() {
float timestep = Time.fixedDeltaTime;
if (stop) {
return;
}
velocity.x += timestep;
thisRigidbody.MovePosition ((Vector3)thisRigidbody.position + velocity*timestep);
}
void OnTriggerEnter2D(Collider2D col) {
stop = true;
}
}