Hoist the Flag
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 32 of 85.
localPosition can be read and changed on every frame, like position. A child that should climb its parent, a cabin up a tower or a flag up a mast, moves along localPosition and compares its local height with the top, so it works wherever the parent stands:
if (transform.localPosition.y < 10)
{
transform.localPosition += new Vector3(0, 2 * Time.deltaTime, 0);
}Compared with position.y instead, the top would move whenever the parent stands higher or lower.
Challenge
MediumHoist the flag up the mast with the up arrow.
- In
Update(), writeif (Input.GetKey(KeyCode.UpArrow) && transform.localPosition.y < 4). - Inside it, add
new Vector3(0, climb * Time.deltaTime, 0)totransform.localPosition.
Press Play and hold the up arrow: the flag climbs to the top of the mast and stops. Then Check.
Try it yourself
using UnityEngine;
public class Hoist : MonoBehaviour
{
public float climb = 1f;
void Start()
{
transform.localPosition = new Vector3(0.6f, 1, 0);
}
void Update()
{
// While the up arrow is held, climb until the height from the Ship is 4
}
}
All lessons in Unity Scripting Basics
1C# Basics in Unity
Hello, UnityVariablesDecimals Need an fText in the ConsoleVariables That RememberIf and ElseCompare NumbersRecap: Coin Collector2Make It Move
Place the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube5Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot8GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch6Transforms and Hierarchy
Parents and ChildrenHoist the FlagScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon9Project: Catch the Star
The CatcherA Falling StarPractice on your own: Unity playground