Hello everyone,
I’m still new to unity and C# and I’m trying to do the courses here at unity learn. I’m trying to make a little game for one of the courses.
So basically I have this cube and I made a character controller for it. it moves around when you press the w,a,s,d keys and when you press shift it goes a bit faster, but what I wanted it to do is to slowly keep getting faster and faster the longer I press the shift button.
I tried to do it on my own but I couldn’t figure it out. This is what I got so far:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CubeController : MonoBehaviour
{
// the player
public GameObject Player1;
// walking forwards
public bool isMoving;
public float verticalMove;
// turning around
public bool isTurning;
public bool horizontalMove;
public float horizontalTurn;
// walking backwards
public bool backwardsCheck;
public float backwardsSpeed;
// running
public bool isRunning;
// increase speed gruadually the more the shift button is pressed
public float accelerationSpeed = 20f;
public float baseRunSpeed = 30f;
public float runSpeed;
//for explosions
public float radius = 5.0F;
public float power = 10.0F;
public void Start()
{
}
public void FixedUpdate()
{
horizontalTurn = 150f * Time.deltaTime;
backwardsSpeed = 5f * Time.deltaTime;
runSpeed = baseRunSpeed;
runSpeed += accelerationSpeed;
if (Input.GetButton("Vertical"))
{
isMoving = true;
verticalMove = Input.GetAxis("Vertical") * Time.deltaTime * 4;
Player1.transform.Translate(0, 0, verticalMove);
}
else
{
isMoving = false;
}
if (Input.GetButton("DKey"))
{
Player1.transform.Rotate(0, horizontalTurn, 0);
isTurning = true;
}
else if (Input.GetButton("AKey"))
{
Player1.transform.Rotate(0, -horizontalTurn, 0);
isTurning = true;
}
else
{
isTurning = false;
}
if (Input.GetButton("SKey") && !isTurning && !isMoving)
{
Player1.transform.Translate(0, 0, -backwardsSpeed);
backwardsCheck = true;
}
else
{
backwardsCheck = false;
}
if (Input.GetButton("RunKey") && !backwardsCheck)
{
Player1.transform.Translate(0, 0, runSpeed * Time.deltaTime);
isRunning = true;
}
else
{
isRunning = false;
}
}
public GameObject explosion; // drag your explosion prefab here
void OnCollisionEnter()
{
Rigidbody rb = GetComponent<Rigidbody>();
Vector3 explosionPos = Player1.transform.position;
if (isRunning)
{
GameObject expl = Instantiate(explosion, transform.position, Quaternion.identity) as GameObject;
Destroy(expl, 3); // delete the explosion after 3 seconds
rb.AddExplosionForce(power, explosionPos, radius, 3.0F);
Console.WriteLine("BOOM!");
}
}
}