• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by mayur.bendale · Oct 29, 2012 at 08:34 AM · snaketail

Snake head should be followed by tail like classic snake game

I have made one script but problem is that snake move like rope, i want to make it move like Classic Snake Game. I have used hing joint to attach tail to snake head.

Here is my script:

 using UnityEngine;
 using System.Collections;
 
 public class snakeHeadMovement : MonoBehaviour 
 {
     public float MovementSpeed =5.0f;
     public float TurnSpeed = 20.0f;
     public GameObject TailPrefab, ApplePrefab;
     private GameObject lastChain=null;
     private float moveSpeed = 1.7f;
     private int counter = 0;
     public int Score = 0, Lives = 3;
 
     void snake_addTail() 
     {
 
        if(lastChain == null)
        lastChain = gameObject;
 
         GameObject newChain  = (GameObject) Instantiate(TailPrefab, lastChain.transform.position - lastChain.transform.forward, Quaternion.identity); 
        newChain.transform.rotation = lastChain.transform.rotation;
        HingeJoint hingeJoint = (HingeJoint) newChain.GetComponent<HingeJoint>();
 
        if(hingeJoint != null) 
        {
        hingeJoint.connectedBody = lastChain.rigidbody;
        lastChain = newChain;
        }
        counter++;
        rigidbody.mass++; // make the head weight greater so it can carry it's tail... lol
        moveSpeed += 0.05f;
     }
 // Use this for initialization
     void Start () 
     {
         snake_addTail();
     }
 
     void OnGUI()
     {
        GUI.color = Color.magenta;
        GUI.Label(new Rect(410, 20, 100, 20), "Score: " + Score);
        GUI.Label(new Rect(490, 20, 100, 20), "Lives: " + Lives);
     }
 
     void OnCollisionEnter(Collision collision) 
     {
 
     if(collision.gameObject.name == "apple" || collision.gameObject.name == "applePrefab(Clone)" ) 
     {
        Destroy(collision.gameObject);
        Score++;  
         snake_addTail();
         return;
     }  
     if((collision.gameObject.tag == "boundry")||(collision.gameObject.name=="tailPrefab(Clone)"))
 
     {
         Lives--;
     }
     }
 
 // Update is called once per frame
 
     void Update () 
     {
        transform.Translate(Vector3.forward * MovementSpeed * Time.deltaTime);
 
 
        if(Input.GetKey(KeyCode.UpArrow))
        {
          transform.Translate ( new Vector3(1,0,1) );
            transform.Rotate(0,180,0);
          transform.Translate ( new Vector3(0,0,1) );
        } 
 
        if(Input.GetKey(KeyCode.RightArrow))
        {
            //transform.Rotate(new Vector3(0,90,0));
 
        }
 
        if(Input.GetKey(KeyCode.LeftArrow))
        {
 //       transform.Rotate(new Vector3(0,-90,0));
 
        }
 
        if(Input.GetKey(KeyCode.DownArrow))
        {    
          transform.Translate ( new Vector3(1,0,1) );
          transform.Rotate(0,180,0);
          transform.Translate ( new Vector3(0,0,-1) );  
        } 
 
 
 
        float r = Random.Range(0, 100);
        if(r > 90 && GameObject.FindWithTag("apple") == null)  
        {
        float range = 5.0f;
        Vector3 pos = new Vector3(Random.Range(-range,range), 0, Random.Range(-range,range));
        Instantiate(ApplePrefab, pos, Quaternion.identity);
        }
     }
 }
Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
2
Best Answer

Answer by sparkzbarca · Oct 29, 2012 at 11:08 AM

the old snake games are basically a grid with each part of the snake occupying a position in the grid.

you can use a 2 or 3 dimensional array to create an arbitrarily sized playing field and then in the array simply store a vector3. thats the position in space occupied by the array.

You move from one part of the array to the next based on input. Try first to simply get a sphere to move along it. Once you have that you can focus on attaching new spheres and then having the having the array store a structure. That struct will have both a position AND a direction.

If the head which is a special part moves it will go to the next position in the array BUT it will also modify the direction of the previous position it was at so that it points toward the new one. Basically when an object moves it will move from where it is to direction. every object will move from where it is to direction except the head. The head will move from where it is to player input and will set direction.

Comment
Add comment · Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image mayur.bendale · Oct 29, 2012 at 11:42 AM 0
Share

@sparkzbarca

Thanx for the answer.. Can you give me some scripting help(C#) because i am new to unity

avatar image SuarescorX · Dec 12, 2013 at 09:47 PM 0
Share

I was trying to do this the same way, but by doing it on the update, the position was almost the same, so both gameObjects where overlapping, then fail. ¿How can i get a distance between them?

avatar image sparkzbarca · Dec 12, 2013 at 10:10 PM 0
Share

vector3.distance(object1.transform.position, object2.transform.position)

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.



Follow this Question

Answers Answers and Comments

11 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Snake Mechanic 0 Answers

SNAKE [Tail] 0 Answers

Tail follow object - getting the point behind an object 0 Answers

snake problem 0 Answers

Snake Head should be Followed by body and tail like classic snake game 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges