Question by
bui_krisztian · Feb 01, 2018 at 05:42 PM ·
collisionrigidbodymoveposition
Moving a cube with RigidBody. MovePostition, it randomly stops moving
When I press the W key, the cube starts going forward, but sometimes it suddenly stops. When I press the W or S key, it doesn't move. It only starts moving when I rotate the cube, but it can stuck again. What causing this issue?
I control the cube in the Ember class. using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Emberscript : MonoBehaviour {
public class Ember
{
public Transform body;
//public Transform lArm, rArm;
public Vector3 movingVector = new Vector3(0, 0, 0);
public int rotation = 0;
public bool falling = false;
public Rigidbody rigidbody;
public Ember(Transform body, Transform lArm, Transform rArm)
{
this.body = body;
//this.lArm = lArm;
//this.rArm = rArm;
}
public void Move()
{
rigidbody.MovePosition(rigidbody.position + Quaternion.Euler(0, rotation, 0) * movingVector * Time.fixedDeltaTime);
body.rotation = Quaternion.Euler(0, rotation, 0);
}
public void Jump()
{
rigidbody.AddForce(Vector3.up * Mathf.Sqrt(2 * -2f * Physics.gravity.y), ForceMode.VelocityChange);
}
}
void UserInput()
{
if (Input.GetKeyDown(KeyCode.W))
{
ember.movingVector += new Vector3(0, 0, 5f);
}
if (Input.GetKeyUp(KeyCode.W))
{
ember.movingVector -= new Vector3(0, 0, 5f);
}
if (Input.GetKeyDown(KeyCode.S))
{
ember.movingVector += new Vector3(0, 0, -5f);
}
if (Input.GetKeyUp(KeyCode.S))
{
ember.movingVector -= new Vector3(0, 0, -5f);
}
if (Input.GetKey(KeyCode.A))
{
ember.rotation += -1;
}
if (Input.GetKey(KeyCode.D))
{
ember.rotation += 1;
}
if (Input.GetKeyDown(KeyCode.Space))
{
ember.Jump();
}
}
void SpawnCircle(float r)
{
float cubeLength = 2 * r * Mathf.PI / 360;
for (int i = 0; i < 360; i++)
{
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.transform.position = Quaternion.Euler(0, i, 0) * new Vector3(0, 0, r);
cube.transform.localScale = new Vector3(cubeLength + 0.05f, 1f, 1f);
cube.transform.rotation = Quaternion.Euler(0, i, 0);
}
}
Ember ember;
public Transform lArm, rArm;
int numberOfCircles = 0;
void Start () {
ember = new Ember(transform,lArm,rArm);
ember.rigidbody = ember.body.GetComponent<Rigidbody>();
}
void Update () {
UserInput();
if(Vector3.Distance(ember.body.position, Vector3.zero) - numberOfCircles * 5 > 0)
{
numberOfCircles++;
SpawnCircle(numberOfCircles * 5);
}
Debug.Log(ember.rigidbody.position + Quaternion.Euler(0, ember.rotation, 0) * ember.movingVector);
}
void FixedUpdate()
{
ember.Move();
}
}
Comment