Unity Space Shooter – Chapter 8 – boundary collider

Create a boundary around the game play area so the shots can be removed from play after they fall off the field.

 

  1. Create a box larger than the play area
    1. Create Cube
    2. Scale it
    3. Make sure it has a box collider
    4. isTrigger is checked
    5. Remove the Cube(mesh filter)
    6. Remove the mesh renderer.
  2. Create script(to handle the trigger) DestroyByBoundary
  3. Edit and add the OnTriggerExit routine.  When triggered, it will destroy the other object.
  4. Easy

Unity Space Shooter – Chapter 7 – fire laser shot from player

Shooting shots.

Create an game object called “shotSpawn” as a child of our player.  This will become the origin for the shot when started, but we need a way to communicate between the object and the c# program, so we make a couple helpers

Edit “PlayerController”

Object:

Positon:

Rotation:

We need a way to fill those in.

In the c#

public GameObject shot; // what gets shot

public Transform shotSpawn; // the object to use to get the shot

In Unity

Make an empty game object called ShotSpawn as a child of the Player object. Adjust it to the tip of the nose.  This is where the initial location comes from.

Drag the bullet from the Prefabs into the new “shot” reference

Drag the ShotSpawn into the new shotSpawn reference

 

That is the setup.

 

Now to shoot.

Instantiate the shot when button is clicked (but include a pause) so we dont fire one every frame

 

REMEMBER * * *  CHANGES TO OBJECT PARAMETERS ARE NOT SAVED UNTIL YOU ARE OUT OF TEST-GAME MODE * * *

 

Yup. Working through the tuts.

Chapter 4.

Background:
Add 3d/quad

  1. Reset origin
  2. Rename it.
  3. Create the mesh renderer(background) texture, by dragging-and-dropping from the textures folder.
  4. Scale it to 15 x 30
  5. Cuts off the bottom of the player.  So set y to -10

  6. It looks all shiny, so we remove the light by going to mesh-renderer, shade: unit/texture

Chaper 5 – move the player using keyboard

Features: c#, and FixedUpdate()

  1. Select The object
  2. Add component – new script and call it PlayerController Best to start visual studio before trying the editor, else the thing get stuck with a “launching” button.(might be why stuff didn’t save when I left too.(?))

  3. We are using  the physics engine so these things are important

  4.  Note – this is what they say to use

I like how they build the variable starting with the prototype then fill each parameter in as they translate them

Then they translate them one by one.  Here we have no Y , so that is 0.  The rest is process of elimination.

Studio complains because 5  doesnt have rigidbody.  Lets do this per the upgrade pdf.

 

We adjust our script accordingly.

 

Make it more responsive by using a public speed variable (and set to 13)

public float speed = 13;

rb.velocity = movement * speed;

 

Limit movement using Clamp function in the FixedUpdate routine.

 

 

Unity SpaceShooter – Chapter 4 – move player with keys

Running a thread in an activity

But first – why? I did it because I wanted to issue a quickie without setting up a service. Some folks on the
internet say to use asyncTask first.

0. Create a way for the running thread to talk with the outside world via messages
1. The class that implements runnable – it is the thing that does the work
2. An instance of thread that has #1’s runnable with it
3. A way for the runnable to communicate with the application
4. Special bonus – shutdown, and restart

In this instance, we will make a runner that ticks the seconds since
the app starts/ends(hooked to the onResume, onPause functions)

0. Create a way for the running thread to talk with the outside world via messages
At the top of the activity declare some message type codes

		public static final int MSG_SEC_INT = 1;

Then the messaage handler inline…

   // The Handler that gets information back from the Socket
        private final Handler mHandler = new Handler() {
        	@Override
        	public void handleMessage(Message msg) {
        		switch (msg.what) {
        			case MSG_SEC_INT:
                                        int ct=msg.arg1;
                                        Log.i(TAG, "Message CT: "+ct);
        				break;
        		}
        	}
        };

1. The class that implements runnable – this is the thing that does the work. Note the graceful exit from the run loop using the isDone variable(only changed in cancel())

        private class TickTick implements Runnable {
                 long count;
                 int isDone;
        	 public TickTick() {
                      count=0;
                      isDone=0;
        	 }

        	 public void run() {

        	        // do this until an exception occurs
        	 	while (isDone==0) {
                              try {
                                  Thread.sleep(1000);
                                  count++;
	 			    mHandler.obtainMessage(MSG_SEC_INT, count,0); // return two generic ints, our count and nothing important(0).  Can be more elaborate like objects, etc see android documentation.
       	 			    .sendToTarget();
                              }catch(InterruptedException iEx){
                                    isDone=1;
                              }
        	 	}
        	 }

        	 /* Call this from the main activity to shutdown the connection */
        	 public void cancel() {
        		 try {
                               // yeah, this is silly for try-catch but you know its useful for io operations,etc.
                               isDone=1;
        		 } 
        		 catch (IOException e) { 
        			 Log.e(TAG, "Error when closing the TickTick");
        		 }
        	 }
        } /* end runnable */

3. A way for the runnable to communicate with the application

// global declaration
         TickTick runner=null;
         Thread tickThread=null;

And in the activities start routine. Good candidates are onStart,onCreate, onResume. I chose onResume.

      runner=new TickTick();
      tickThread=new Thread(runner;
      tickThread.start();  // 

4. Special bonus for shutdown
best place for this is onPause, onStop, onDestroy – we use on Destroy

public void onPause(){
/* // use me to interrupt the thread without waiting for nice clean shutdown
      if(tickThread!=null){
           thread.interrupt();
      }
*/
      runner.cancel(); // use cancel to give the thread a chance to die naturally
      thread.join(5000);  // and give it 5 seconds to try
      super.onPause();
}

Basic Graphics Stuff

Load image from URL and paste it into your own bitmap

  • Load Image from URL
  • Convert Image to BASE64 – easy storage on sqlite database
  • Convert image to something that can be drawn
    • Of course this is just a toy since converting to base64 and back is silly

      public static Bitmap getBitmapFromURL(String src) {
      	Bitmap ret=null;
          try {
              URL url = new URL(src);
              HttpURLConnection connection = (HttpURLConnection) url.openConnection();
              connection.setDoInput(true);
              connection.connect();
      // get the image
              InputStream input = connection.getInputStream();
      // convert it into byte[] in prep of convert to base64
              byte[] rawimage=readBytes(input); 
      // convert to base64 string
              String x64=Base64.encodeToString(rawimage, Base64.DEFAULT);
      // convert back from base64 
              byte[] ext=Base64.decode(x64, Base64.DEFAULT);
      // render the byte array as a bitmap
              ret = BitmapFactory.decodeByteArray(ext, 0, ext.length);
          } catch (IOException e) {
              e.printStackTrace();
          }
          return ret;
      }
      
      public void paint() throws Exception{
      	   Canvas c = new Canvas(bitmap);
      	   Paint p=new Paint(Color.BLACK);
      	   c.drawColor(Color.WHITE);
      	   p.setTextSize(80);
      	   c.drawText("HEY",50,50,p);
      	   try {
      			//Bitmap timg=getBitmapFromURL("http://www.uclick.com/puzzles/tmjmf/puzzles/tmjmf130501.gif");
      	   //c.save();
      	   c.scale(3f, 3f, 0, 0);
      	   c.drawBitmap(timg, 200, 100, null);
      	   } catch(Exception e){
      		   e.printStackTrace();   
      	   }
      	   //c.restore();
      	
      }
      

10 Weeks to a Better Me

Imagine a skinny balding man walking across a broad flat plain.  The sky is the blue of mid May and the terrain speckled.

He doesn’t wear much.  Only a simple cloth around his privates and on his hip,a bag made of animal skins containing only the most essential items.    The setting sun tints his face orange and reflects off the long staff he uses when he walks.  It is a little taller than he is, thin, light and sharpened at one end.

The wind has been blowing all day, but now as the sun sets, a calm befalls the entire scene.  The moment is not lost on the man, so he stands still and closes his eyes.  At the edge of perception he feels the world around him; countless animals scurry through the underbrush, looking for shelter for the night.  In countless burrows and holes nocturnal creatures are awake and preparing for the evening ahead. He is aware of everything that is alive and moving within the world around him.  He is perfectly in-step with the nature around him and could, if he desired, stand in that pose for hours.

In the near perfect silence he perceives a low sound.  It is a sound below the hum of the insects, although they flap to the same rhythm.  It is a sound below the beat of the last sparrows and first bats.  It is low and constant and as he opens his eyes to the world around him, he notices the sound of his own voice echoing the sound of the world.

The picture I just described is easy to see in the mind’s eye.  It stirs up feelings, conjures impressions, and reminds you of some undefinable quality.   Like those countless creatures waiting in their burrows,  you are astir and that is why you are here.   How would I know?  I’ve been there.  I have spent all the years of my life dedicated to conscious change and am happy to report some amazing results.

Am I enlightened?  Hardly!  To admit enlightenment,  aside from the ego-derived  slavery it would impose on me, would imply that I’ve reached some pinnacle, some high point from which to watch the world.    I am happy to report that  I will continue to learn and change all the days of my life.  So much the better, because the alternative seems just bleak.

So, why write?   There are many reasons both personal and altruistic.

What can you accomplish in 10 weeks?  Shorter than most college courses.  How much homework?

 

Shortcut to Contentment…

Become comfortable in your own skin.   Find out where you being and where the world ends.

When you need inspiration, just look around.

 

What this course is about…

This course is about self exploration.  There are aisles dedicated to this topic at your local bookstore or amazon.com.  There are many great

The tools in your bag…

This course is designed to get you minimal insight with

Get a blank book to write in.  It will become a mirror as you journey.  How elaborate?  Clare, my eldest daughter, uses a richly tooled leather book jacket  which she replaces with filler as it gets full.  Sarah uses small spiral bound notebooks and plasters the covers with stickers.   I prefer the cheap essay books you find at Target or Dollar Tree.  The idea is to get something that will become a snapshot of you.  If the pages are loose,  like a three ringed binder, you might not get the sense of any permanence.

Get a book.  Call it a diary, dream diary, journal.

Like the man in the image, you do not need

Exercise I

Write a title, the date and a declaration.  People sometimes get hung-up on this one, so don’t worry of you feel uncomfortable.  Do as much as you can.  If nothing else write the date on the first page.

 

Exercise II –

Bonus Exercise –

 

 

 

Wandering Nude in a Forest

What goes into making an Android application?   Java for the computing.  Pictures, Icons and other resources for the eye/ear candy. A place to put all your button and title labels for easy language translation.  And a bunch of  XML to bind it all together.

The granddaddy of the binding files is “AndroidManifest.xml”

AndroidManifest.xml is the connector between the xml resource files and java programming.   For example. If you create a new screen(Activity) called “about”.  You will define the screen layout in the res/layout/about.xml file.   You will also create a new activity called  AboutActivity.java.  If tried to run it before updating the manifest,  the about screen would not be available.   Remember to add a new activity called .AboutActivity under the Application tab of the manifiest editor.

 

 

Their Words Not Mine…OK…Mine

Because I am learning and this is my blog, I reserve the right to be wrong, very wrong, or just plain Wrong!  Consider this your one and only apology.  Sorry about that.

Getting familiar with Android terminology and structure…

A bit about their design philosophy.  The have two:  Connecting things.  No need to invent the wheel over and over. If you need an email app, don’t roll your own, just ask Android if there is a suitable app to handle it.  Customize it.  The user is not locked into a single way of getting a job done.   Is the default browser crappy?  Get a different one.  They also really like protecting data.  Each application runs in its own space. To gain access to other data,  permission must be granted.

Pick that app apart.

At any one time, applications typically either collect or present data.  A user can’t handle more than one screenfull at a time.   Applications that require more than one screen, must provide a method.

Applications may do more than one thing.

Activities represent a unit of work within an application – typically one screen full.   It may be data entry, it may be streaming netflix.

Services represent the background processing where the user’s active participation is not required.   When I turn on my gps,  that is a service.  So is streaming Pandora audio while I surf using the browser.

Broadcast Receivers will perform a task for you.  When I tap on an url link inside e-mail, it starts in Opera.  Email declares a need and Opera, being registered as a Broadcast Receiver for for web pages, performs the task.  Does that mean that all broadcast-receivers are content providers?  I think one is data the other is program.   Android describes the situation where an app needs a picture, spins the task off to the camera, and when done it returns to the app -photo in cache ready to go.  Powerful stuff.

Content providers  – handle the chore of managing common data.  When you start a new instant message,  the contact manger provides the default list of who you can talk to.

These four categories of components represent the core of Android structure.   But how do they talk?   Mostly through a message passing system known as an Intent.  The intent is the binding agent between application bits.  For example, once the contact is selected, the uri is returned to the originating app.

With broadcast recievers, you don’t know exactly where the application is going next, so it uses the ContentResolver to provide a way for apps to respond.

Each of these components has a variety of ways they are called, but all use intent as the conduit for communication between.