How To Make Player Transform Into Ball and Back Using Space Key
I am creating a game where the player will be able to roll up into a ball and roll around in the level by pressing the space key. What I want to know is how to change the model of the player into a ball by pressing the space key and then back again when you press the space key a second time.
FYI I am using C#
Answer by dardamavet · Jul 10, 2017 at 02:53 PM
Hey @TheGreenHornut, this was a fun experiment :)
This script will inflate your model to a ball and back.
In the attached script you can should set up the center of the model. The model will inflate around this point, so make sure it's inside your model. You can set the radius of the ball and the transitionTime.
The script will put each vertice in distance of radius from the center, with the same direction it had before.
I'm assuming you know how to handle space-bar pressing, but if not, please check out unity docs: https://docs.unity3d.com/ScriptReference/Input.GetKeyDown.html
Enjoy
using UnityEngine;
[RequireComponent(typeof(MeshFilter))]
public class inflateModel : MonoBehaviour {
public float transitionTime = 5;
public float radius = 10;
public Vector3 center = Vector3.zero;
private float timeLeft;
private bool inflate = true;
private Vector3[] originalVertices;
private Vector3[] inflatedVertices;
private Vector3[] currentVertices;
private Mesh mesh;
void Start()
{
timeLeft = transitionTime;
mesh = GetComponent<MeshFilter>().mesh;
originalVertices = mesh.vertices;
inflatedVertices = new Vector3[originalVertices.Length];
currentVertices = new Vector3[originalVertices.Length];
for (int i = 0; i < originalVertices.Length; i++)
{
inflatedVertices[i] = (originalVertices[i] - center).normalized * radius + center;
currentVertices[i] = originalVertices[i];
}
}
void Update () {
timeLeft -= Time.deltaTime;
if (timeLeft <= 0)
{
timeLeft = transitionTime;
inflate = !inflate;
}
float t = timeLeft / transitionTime;
if (!inflate)
t = 1 - t;
for (int i = 0; i < currentVertices.Length; i++)
{
currentVertices[i] = Vector3.Lerp(inflatedVertices[i], originalVertices[i], t);
}
mesh.vertices = currentVertices;
mesh.RecalculateBounds();
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612121633im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Please explain a switch statement? 4 Answers
Button bool doesn´t work correctly weird 1 Answer
Help with footstep box triggers within another box trigger. 0 Answers
Imported Models Not Rendering Correctly? 5 Answers
How to create a plot system 0 Answers