I need a full set of scripts to create a psychological horror game in Unity called Mr.…
- User
I need a full set of scripts to create a psychological horror game in Unity called Mr. John. The core character, Mr. John, is an unsettling, humanoid figure who interacts with the player by following them or guiding them to specific points in the environment to complete puzzles. You, the AI, should create the necessary scripts from scratch, including naming conventions and logic. Please ensure that all the scripts work together to create a seamless gameplay experience.
Here are the core elements and mechanics of the game, with clear instructions for how they should function. You can decide how best to implement the details, but ensure they adhere to the core ideas:
Core Mechanic: Mr. John’s Behavior Following the Player:
Mr. John should be able to follow the player character at a set distance. The player’s camera (first-person or third-person) should be the reference point for Mr. John’s movement, and Mr. John should smoothly navigate behind the player using Unity’s NavMesh system. Mr. John should maintain a certain distance when following the player but should always be within visual range to maintain the eerie, unsettling presence. Allow for toggling this behavior on and off based on events in the game, such as completing puzzles or when the player interacts with the environment. Guiding the Player to a Destination:
Mr. John can also move to a specific point in the game world (set by a destination or objective) when required. The script should include a method to switch between "follow player" mode and "move to destination" mode. The destination point can either be set via UnityEvents or a Transform input. Visibility and Animation:
Mr. John should have the ability to toggle his visibility, giving the impression that he appears and disappears in specific moments. This toggle could be based on in-game triggers or player actions. Mr. John should also have an eerie look and feel. His animations should reflect this by using an Animator component, with specific animation states (e.g., idle, moving, etc.). Ensure visibility changes and animations are synchronized, such that when Mr. John appears, his body gradually fades in, and his movements are slightly unnatural but not overtly monstrous. Looking at the Player or a Target:
Mr. John should always face the player (or the destination) when either following or moving to a point. The rotation should be smooth to avoid breaking immersion and use Quaternion functions to ensure smooth transitions between angles. When following the player, Mr. John’s body should rotate to face them while keeping his distance behind them. Puzzle Interaction Puzzles and Task Completion:
In the game world, the player interacts with various puzzles and tasks that Mr. John will guide them toward. Each puzzle should have a script attached to it that tracks whether the puzzle has been completed. Once completed, the puzzle sends a signal to Mr. John’s controller to trigger a new behavior (e.g., move to the next destination, make Mr. John disappear, or unlock a door). Prefab Setup:
Create a script for each puzzle or object that allows it to track its completion state and invoke methods when the puzzle is finished. This should be flexible so that different puzzles can be created as prefabs with this script attached. Ensure the puzzle script can interface with Mr. John’s controller (likely via UnityEvents or delegates) to trigger behavior changes when the puzzle is solved. Tools and Structure NavMesh Movement:
Use Unity’s NavMesh system to handle Mr. John’s movement when following the player or moving to a destination. Make sure the pathfinding is smooth and takes into account obstacles and environmental factors. Mr. John should be able to start and stop moving fluidly based on conditions (e.g., freeze when idle, unfreeze when moving). Player Reference:
Mr. John’s behavior should reference the player’s position, either through their camera or another object attached to the player. If the player object is not assigned, default to Camera.main. Ensure Mr. John’s movement respects this reference and always acts relative to the player’s position. Public Methods and UnityEvent Support Public Methods for Flexibility:
Create public methods for all core actions that can be called via UnityEvents or other scripts, including: Toggling between following the player and moving to a destination. Setting a new destination point for Mr. John to move toward. Toggling visibility on and off. Freezing and unfreezing Mr. John’s movement. Detecting and responding to puzzle completion events. Smooth Integration with Unity:
The code should be modular and easy to integrate into Unity. Ensure that key variables (like follow distance, speed, visibility states, etc.) are exposed in the Unity Inspector so they can be adjusted easily. Any input from UnityEvents should be designed in a way that allows non-programmers to trigger Mr. John’s behaviors during gameplay without modifying the code. Error Handling and Robustness Fallbacks and Error Handling: If player objects or destination points are not assigned, the code should handle these cases gracefully by falling back on sensible defaults (e.g., using Camera.main as a reference for Mr. John’s movement). Make sure all movement and behavior transitions (such as switching between follow mode and destination mode) are smooth and don’t result in jittery or unnatural movement. You, the AI, can decide on how to name all variables, methods, and classes in a way that makes sense based on the functionality. Please ensure that the scripts are modular, reusable, and integrate smoothly into Unity. I will handle object configuration in Unity, so the code should focus on creating the logic and ensuring all parts of the system work cohesively together. Make sure all scripts are complete and can interact with each other correctly."
- Assistant
Certainly! Below are the C# scripts required to implement the core mechanics of your psychological horror game, Mr. John, in Unity. These scripts are designed to be modular, reusable, and integrate smoothly into Unity. They allow Mr. John to follow the player, guide them to specific destinations, interact with puzzles, and exhibit eerie behaviors as specified.
Scripts Overview:
-
MrJohnController.cs: Controls Mr. John's behaviors, including following the player, moving to destinations, toggling visibility, handling animations, and responding to puzzle completion events.
-
PuzzleController.cs: A base script for puzzles, tracking their completion state and interfacing with Mr. John via UnityEvents.
-
ExamplePuzzle.cs: An example puzzle script inheriting from
PuzzleController, showcasing how to implement specific puzzle logic. -
MrJohnAnimationController.cs: Handles Mr. John's animations and visibility transitions.
MrJohnController.cs
using UnityEngine; using UnityEngine.AI; using UnityEngine.Events; [RequireComponent(typeof(NavMeshAgent))] public class MrJohnController : MonoBehaviour { [Header("Movement Settings")] public Transform playerTransform; public float followDistance = 5f; public float movementSpeed = 3.5f; public float rotationSpeed = 5f; public bool isFollowingPlayer = false; public bool isMovingToDestination = false; public bool isFrozen = false; [Header("Visibility Settings")] public bool isVisible = true; public UnityEvent onAppear; public UnityEvent onDisappear; [Header("Destination Settings")] public Transform destinationPoint; [Header("Animation Settings")] public Animator animator; private NavMeshAgent navMeshAgent; private Transform initialPlayerTransform; private void Awake() { navMeshAgent = GetComponent<NavMeshAgent>(); if (playerTransform == null) { if (Camera.main != null) playerTransform = Camera.main.transform; else Debug.LogError("MrJohnController: No playerTransform assigned and no main camera found."); } navMeshAgent.speed = movementSpeed; navMeshAgent.stoppingDistance = followDistance; initialPlayerTransform = playerTransform; } private void Update() { if (isFrozen || !isVisible) { navMeshAgent.isStopped = true; animator.SetBool("isMoving", false); return; } if (isFollowingPlayer && playerTransform != null) { FollowPlayer(); } else if (isMovingToDestination && destinationPoint != null) { MoveToDestination(); } else { navMeshAgent.isStopped = true; animator.SetBool("isMoving", false); } HandleRotation(); } private void FollowPlayer() { navMeshAgent.isStopped = false; navMeshAgent.SetDestination(playerTransform.position); animator.SetBool("isMoving", true); } private void MoveToDestination() { navMeshAgent.isStopped = false; navMeshAgent.SetDestination(destinationPoint.position); animator.SetBool("isMoving", true); } private void HandleRotation() { Vector3 targetDirection; if (isFollowingPlayer && playerTransform != null) { targetDirection = playerTransform.position - transform.position; } else if (isMovingToDestination && destinationPoint != null) { targetDirection = destinationPoint.position - transform.position; } else { return; } Vector3 direction = Vector3.RotateTowards(transform.forward, targetDirection, rotationSpeed * Time.deltaTime, 0.0f); transform.rotation = Quaternion.LookRotation(direction); } #region Public Methods public void ToggleFollowPlayer(bool shouldFollow) { isFollowingPlayer = shouldFollow; isMovingToDestination = !shouldFollow; if (shouldFollow) { destinationPoint = null; } navMeshAgent.ResetPath(); } public void SetDestination(Transform newDestination) { destinationPoint = newDestination; isMovingToDestination = true; isFollowingPlayer = false; navMeshAgent.ResetPath(); } public void ToggleVisibility(bool visible) { isVisible = visible; if (isVisible) onAppear.Invoke(); else onDisappear.Invoke(); } public void FreezeMovement(bool freeze) { isFrozen = freeze; } public void ResetPlayerReference() { playerTransform = initialPlayerTransform; } public void OnPuzzleCompleted() { // Define behavior when a puzzle is completed // Example: Move to next destination or disappear } #endregion }
PuzzleController.cs
using UnityEngine; using UnityEngine.Events; public class PuzzleController : MonoBehaviour { [Header("Puzzle Settings")] public bool isCompleted = false; public UnityEvent onPuzzleCompleted; [Header("Mr. John Interaction")] public MrJohnController mrJohnController; public void CompletePuzzle() { if (!isCompleted) { isCompleted = true; onPuzzleCompleted.Invoke(); if (mrJohnController != null) { mrJohnController.OnPuzzleCompleted(); } else { Debug.LogWarning("PuzzleController: MrJohnController is not assigned."); } } } }
ExamplePuzzle.cs
using UnityEngine; public class ExamplePuzzle : PuzzleController { // Example puzzle logic private void Update() { // Placeholder for puzzle completion condition if (Input.GetKeyDown(KeyCode.E)) // Example condition { CompletePuzzle(); } } }
MrJohnAnimationController.cs
using UnityEngine; using System.Collections; public class MrJohnAnimationController : MonoBehaviour { [Header("Visibility Settings")] public Renderer[] renderers; public float fadeDuration = 2f; private MrJohnController mrJohnController; private Coroutine visibilityCoroutine; private void Awake() { mrJohnController = GetComponent<MrJohnController>(); if (mrJohnController == null) { Debug.LogError("MrJohnAnimationController: MrJohnController component not found."); } } private void OnEnable() { mrJohnController.onAppear.AddListener(FadeIn); mrJohnController.onDisappear.AddListener(FadeOut); } private void OnDisable() { mrJohnController.onAppear.RemoveListener(FadeIn); mrJohnController.onDisappear.RemoveListener(FadeOut); } private void FadeIn() { if (visibilityCoroutine != null) StopCoroutine(visibilityCoroutine); visibilityCoroutine = StartCoroutine(Fade(0f, 1f)); } private void FadeOut() { if (visibilityCoroutine != null) StopCoroutine(visibilityCoroutine); visibilityCoroutine = StartCoroutine(Fade(1f, 0f)); } private IEnumerator Fade(float startAlpha, float endAlpha) { float elapsedTime = 0f; while (elapsedTime < fadeDuration) { float alpha = Mathf.Lerp(startAlpha, endAlpha, elapsedTime / fadeDuration); SetRenderersAlpha(alpha); elapsedTime += Time.deltaTime; yield return null; } SetRenderersAlpha(endAlpha); } private void SetRenderersAlpha(float alpha) { foreach (Renderer rend in renderers) { foreach (Material mat in rend.materials) { Color color = mat.color; color.a = alpha; mat.color = color; } } } }
Explanation and Integration Details
MrJohnController.cs
- Purpose: Controls Mr. John's core behaviors:
- Following the player.
- Moving to a designated destination.
- Handling visibility.
- Responding to puzzle completion events.
- Key Public Variables:
playerTransform: Reference to the player or camera.followDistance: The distance Mr. John maintains from the player.movementSpeed: Speed at which Mr. John moves.isFollowingPlayer: Toggles following behavior.isMovingToDestination: Toggles moving to a destination.isVisible: Toggles visibility.
- Public Methods:
ToggleFollowPlayer(bool): Starts/stops following the player.SetDestination(Transform): Sets a new destination for Mr. John to move toward.ToggleVisibility(bool): Toggles Mr. John's visibility.FreezeMovement(bool): Freezes/unfreezes Mr. John's movement.OnPuzzleCompleted(): Method to be called when a puzzle is completed.
Integration Steps:
-
Assign Player Reference:
- In the Unity Inspector, assign the
playerTransformto the player's camera or another relevant transform. - If left unassigned, the script defaults to
Camera.main.
- In the Unity Inspector, assign the
-
Animator Component:
- Assign the
animatorvariable to Mr. John's Animator component. - Ensure animation states
isMovingare set up in the Animator controller.
- Assign the
-
Event Handling:
- Use UnityEvents
onAppearandonDisappearto handle visibility transitions through theMrJohnAnimationController.
- Use UnityEvents
-
NavMeshAgent:
- Ensure Mr. John has a
NavMeshAgentcomponent attached. - Bake the NavMesh in your scene to enable pathfinding.
- Ensure Mr. John has a
PuzzleController.cs
- Purpose: Acts as a base class for all puzzle scripts.
- Key Public Variables:
isCompleted: Tracks whether the puzzle has been completed.onPuzzleCompleted: UnityEvent invoked upon puzzle completion.mrJohnController: Reference to Mr. John's controller to trigger behaviors upon puzzle completion.
- Public Methods:
CompletePuzzle(): Marks the puzzle as completed and invokes necessary events.
Integration Steps:
-
Create Puzzle Prefabs:
- Use
PuzzleControlleras a base when creating new puzzle scripts. - Attach puzzle-specific logic in derived classes (e.g.,
ExamplePuzzle).
- Use
-
Assign Mr. John Reference:
- In the Inspector, assign
mrJohnControllerto have puzzles communicate with Mr. John.
- In the Inspector, assign
-
Event Handling:
- Use
onPuzzleCompletedto trigger any additional behaviors or sound effects upon puzzle completion.
- Use
ExamplePuzzle.cs
- Purpose: Provides an example of implementing a puzzle using
PuzzleController. - Integration:
- Replace the placeholder condition with your puzzle logic.
- Call
CompletePuzzle()when the puzzle's completion conditions are met.
MrJohnAnimationController.cs
- Purpose: Handles Mr. John's visibility transitions and animations.
- Key Public Variables:
renderers: Array of Mr. John's renderers to control visibility.fadeDuration: Duration of the fade-in and fade-out effects.
- Integration Steps:
-
Assign Renderers:
- In the Inspector, assign all renderers (e.g., MeshRenderers, SkinnedMeshRenderers) associated with Mr. John to the
renderersarray.
- In the Inspector, assign all renderers (e.g., MeshRenderers, SkinnedMeshRenderers) associated with Mr. John to the
-
Event Subscription:
- The script automatically subscribes to
onAppearandonDisappearevents fromMrJohnController.
- The script automatically subscribes to
-
Material Setup:
- Ensure Mr. John's materials support transparency (use shaders that handle alpha values).
How Scripts Interact
-
Puzzle Completion:
- When a puzzle is completed,
PuzzleControllerinvokesonPuzzleCompletedand callsmrJohnController.OnPuzzleCompleted(). - This can trigger Mr. John to change behaviors, such as moving to a new destination or changing visibility.
- When a puzzle is completed,
-
Mr. John Behaviors:
- The
MrJohnControllerscript uses public methods that can be called from puzzles, triggers, or other game events via UnityEvents. - Example: A completed puzzle can make Mr. John disappear by calling
mrJohnController.ToggleVisibility(false);.
- The
-
Visibility and Animations:
MrJohnAnimationControllerhandles the visual aspects when Mr. John's visibility changes, ensuring smooth fade transitions.
Error Handling and Robustness
-
Null Checks:
- The scripts include checks to ensure that key references (like
playerTransformandmrJohnController) are assigned. - If references are missing, the scripts default to sensible fallbacks or log errors to assist in debugging.
- The scripts include checks to ensure that key references (like
-
Smooth Transitions:
- Movement and rotation use smooth interpolation to prevent jittery behavior.
- NavMeshAgent's
stoppingDistanceis set to maintain the desired follow distance.
-
Inspector Exposure:
- All key variables are exposed in the Inspector for easy adjustment:
- Movement speeds, distances, visibility flags, and references.
- UnityEvents allow designers to set up triggers and responses without modifying code.
- All key variables are exposed in the Inspector for easy adjustment:
Usage Example
-
Setting Up Mr. John in the Scene:
- Add Mr. John to your scene and attach the
MrJohnController,NavMeshAgent,Animator, andMrJohnAnimationControllerscripts. - Assign necessary references in the Inspector.
- Add Mr. John to your scene and attach the
-
Creating a Puzzle:
- Create a new puzzle by creating a script that inherits from
PuzzleController. - Implement the puzzle logic and call
CompletePuzzle()when appropriate. - Place the puzzle object in the scene and assign
mrJohnController.
- Create a new puzzle by creating a script that inherits from
-
Designing Behaviors:
- Use UnityEvents to define what happens when the puzzle is completed.
- For example, link the puzzle's
onPuzzleCompletedtomrJohnController.SetDestination(nextDestination).
-
Triggering Visibility Changes:
- To make Mr. John appear or disappear, use
mrJohnController.ToggleVisibility(true or false)in response to game events.
- To make Mr. John appear or disappear, use
Conclusion
These scripts provide a foundation for implementing Mr. John's behaviors and puzzle interactions in your Unity game. By exposing key variables and utilizing UnityEvents, they offer flexibility and ease of integration, allowing designers and non-programmers to adjust behaviors and responses directly in the Unity Editor.
Feel free to customize and extend these scripts to suit the specific needs of your game. If you have any questions or need further assistance, don't hesitate to ask!
-