0
votes

I sticked my character to an empty object and applied Rigidbody, script to that empty object(To change the pivot).

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

public class main_character : MonoBehaviour { public float speed;

private float max_vel = 4f;
private bool grounded = true;
private bool flip = true;
private Rigidbody2D main_vel;

private void Awake()
{
    main_vel = GetComponent<Rigidbody2D>();
}

void FixedUpdate()
{
    float now_vel = Mathf.Abs(main_vel.velocity.x);

    if (Input.GetKey("d") && flip)
    {
        flip_side();
        if (now_vel < max_vel)
        {
            main_vel.AddForce(new Vector2(speed, 0f) * Time.deltaTime);
        }
    }
    if(Input.GetKey("a") && !flip)
    {
        !flip_side();
        if (now_vel < max_vel)
        {
            main_vel.AddForce(new Vector2(-speed, 0f) * Time.deltaTime);
        }
    }
}


void flip_side()
{
    flip = !flip;
    transform.Rotate(0f, 180f, 0f);
}

}

1
It looks like you never set a value for speed. You just declare the variable, which means it will have the default value of 0.HumanWrites
@HumanWrites since it is public it is serialized and you can edit the value via the Inspector within UnityderHugo

1 Answers

0
votes

you either need to add a speed value to the top of the class, or dynamically generate it. I would also put an exception or debug that catches when you press the button while speed is set to zero. if speed accelerates you're going to need to build it or call it in update and give it an initial speed + speed based on delta time. I would also clamp it to max speed there instead, as it prevents large values being tracked by the game engine.

--Regarding an empty parent situation, If there is no physics components, the child should retain the motion of it's parent. That being said, you must have a rigidbody to add force to. You look like you might be using 2d so I have less experience with those rigidbodies, but I imagine it would have to not be kinematic to accept force as you are doing. After checking for that, I would maybe add some debug that posts your vector2 and speed from inside your max_vel check.