Hi! I just started learning Unity and C#(I am an illustrator, never programmed before) this week!
I am loving it, it’s hard to sleep now… thinking about gamedesign/codes! ![]()
So I started with a plataform 2D game, just to learn basic stuff.
I made a ball that runs automatically and when hits the wall, switch direction. Also worked on Jump with click. Ok…
I am trying now to add a SlowMotion when the player is Holding Space. Worked ok, but… it seems to affect the physics and the trajectory of the jump is changed:
Red line = normal trajectory
Blue line = slowmotion trajectory after Space is pressed.
(Link of the img if the attach doesn’t wok: Dropbox - File Deleted - Simplify your life)
Here is the code:
using UnityEngine;
using System.Collections;
public class HeroController : MonoBehaviour {
Rigidbody2D myBody;
public float jumpHeight = 1700f;
public float moveSpeed = 350f;
public bool moveRight;
public Transform groundCheck;
public float groundCheckRadius;
public LayerMask whatIsGround;
private bool grounded;
// Mudar Direção
public Transform wallCheck;
public float wallCheckRadius;
public LayerMask whatIsWall;
public bool hittingWall;
public float slowMotionSpeed = 0.2f;
private bool doubleJumped;
void Start () {
myBody = GetComponent<Rigidbody2D> ();
}
void FixedUpdate(){
grounded = Physics2D.OverlapCircle (groundCheck.position, groundCheckRadius, whatIsGround);
hittingWall = Physics2D.OverlapCircle (wallCheck.position, wallCheckRadius, whatIsWall);
}
void Update () {
if (hittingWall){
moveRight = !moveRight;
}
if (moveRight) {
transform.localScale = new Vector3 (-1f, 1f, 1f);
myBody.velocity = new Vector2 (-moveSpeed * Time.deltaTime, myBody.velocity.y);
} else {
transform.localScale = new Vector3 (1f, 1f, 1f);
myBody.velocity = new Vector2 (moveSpeed * Time.deltaTime, myBody.velocity.y);
}
if (grounded) {
doubleJumped = false;
}
if (Input.GetMouseButtonDown(0) && grounded) {
myBody.velocity = new Vector2 (myBody.velocity.x, jumpHeight);
}
if (Input.GetMouseButtonDown(0) && !doubleJumped && !grounded) {
myBody.velocity = new Vector2 (myBody.velocity.x, jumpHeight);
doubleJumped = true;
}
// Test SlowMotion
if (Input.GetKey (KeyCode.Space)) {
Time.timeScale = slowMotionSpeed;
// Time.fixedDeltaTime = slowMotionSpeed * 0.02f;
} else {
Time.timeScale = 1;
}
}
}
I read somewhere about trying to use the Time.fixedDeltaTime to solve the problem, but I couldn’t make it work.
Anyone can help?
Is there a better way to create this SlowMotion?
The idea is that it affects all the game (hero, enemies, moving objects, etc…)
Thank you!
