Facebook
From Augustus, 1 Month ago, written in C#.
Embed
Download Paste or View Raw
Hits: 129
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class controlDog : MonoBehaviour
  6. {
  7.     [SerializeField] private float moveSpeed;
  8.     [SerializeField] private float leftLimit;
  9.     [SerializeField] private float rightLimit;
  10.     [SerializeField] private float forwardLimit;
  11.     [SerializeField] private float backwardLimit;
  12.     private GameObject carriedBall;
  13.  
  14.     // Update is called once per frame
  15.     void Update()
  16.     {
  17.         float horizontalInput = Input.GetAxis("Horizontal");
  18.         float verticalInput = Input.GetAxis("Vertical");
  19.  
  20.         // Calculate the movement direction
  21.         Vector3 moveDirection = new Vector3(horizontalInput, 0f, verticalInput);
  22.  
  23.         // Check if there is any input
  24.         if (moveDirection != Vector3.zero)
  25.         {
  26.             // Rotate the dog to face the movement direction
  27.             transform.LookAt(transform.position + moveDirection);
  28.         }
  29.  
  30.         // Move the dog in the facing direction
  31.         transform.Translate(moveDirection.normalized * moveSpeed * Time.deltaTime, Space.World);
  32.  
  33.         // Limit the position to the specified range
  34.         LimitPosition();
  35.     }
  36.  
  37.     void LimitPosition()
  38.     {
  39.         // Limit the position in the X-axis
  40.         transform.position = new Vector3(
  41.             Mathf.Clamp(transform.position.x, leftLimit, rightLimit),
  42.             transform.position.y,
  43.             transform.position.z
  44.         );
  45.  
  46.         // Limit the position in the Z-axis
  47.         transform.position = new Vector3(
  48.             transform.position.x,
  49.             transform.position.y,
  50.             Mathf.Clamp(transform.position.z, backwardLimit, forwardLimit)
  51.         );
  52.     }
  53. }
  54.