Play snake game online
Mouse position is captured to drive the snake. SmoothFollowTarget script is used to follow a captured mouse position, as well as for the tail to follow ancestor cell and a head of the snake.
Check out the Unity3D project files from here: https://dl.dropboxusercontent.com/u/50151183/blog/unity/SnakeSample/SnakeSample.zip
Code:
Mouse position is captured to drive the snake. SmoothFollowTarget script is used to follow a captured mouse position, as well as for the tail to follow ancestor cell and a head of the snake.
Check out the Unity3D project files from here: https://dl.dropboxusercontent.com/u/50151183/blog/unity/SnakeSample/SnakeSample.zip
Code:
using UnityEngine; using System.Collections; ////// Smooth follow target /// Used to follow a mouse position as well as for tyhe tail to follow its ancestor /// [RequireComponent(typeof(CharacterController))] public class SmoothFollowTarget : MonoBehaviour { public Transform target; public float distance=3; public float speed = 40; //public float rotationDamping=0.2f; private CharacterController controller; // Use this for initialization void Awake () { controller = GetComponent<CharacterController>() } // Update is called once per frame void Update () { //return; // Early out if we don't have a target if (!target) return; // Always look at the target transform.LookAt(target); // Set the position of the camera on the x-z plane to: // distance meters behind the target var newPos = target.position - transform.forward * distance; newPos.y =1; var speedVector = newPos - transform.position; speedVector.y = 0; if (speedVector.magnitude>distance) controller.SimpleMove(speedVector.normalized * speed); } }