AI scripts for autopilot, rotate to face object and distance/angle calculations

Here are scripts to help with AI for
Autopilot
Rotate to face an object
Calculate distance between two objects
Calculate angle of two objects

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

// A very simplistic car driving on the x-z plane.

public class Drive : MonoBehaviour
{
    
    public float speed = 10.0f;
    float autoPilotSpeed = 5.0f;
    public float rotationSpeed = 100.0f;
    public GameObject gasCan;
    bool autoPilotMode = false;

  

    // mathematical equations for AI machine learning------------------------

    void CalculateDistance()
    {
        Vector3 tankPosition = this.transform.position;
        Vector3 gasCanPosition = gasCan.transform.position;

        float distance = Mathf.Sqrt(Mathf.Pow(tankPosition.x - gasCanPosition.x,2) + Mathf.Pow(tankPosition.y - gasCanPosition.y,2) + Mathf.Pow(tankPosition.z - gasCanPosition.z, 2));

        float unityDistance = Vector3.Distance(tankPosition, gasCanPosition);   

        Debug.Log("Distance: " + distance.ToString());
        Debug.Log("Unity Distance: " + unityDistance.ToString());
    }


    void CalculateAngle()
    {
        Vector3 tankAngle = this.transform.up;
        Vector3 gasCanAngle = gasCan.transform.position - this.transform.position;

        float dot = tankAngle.x * gasCanAngle.x + tankAngle.y * gasCanAngle.y;// this didnt work, not correct
        float angle = Mathf.Acos(dot / (tankAngle.magnitude * gasCanAngle.magnitude));

        Debug.Log("Angle: " + angle * Mathf.Rad2Deg);
        Debug.Log("Unity Angle: " + Vector3.Angle(tankAngle, gasCanAngle)); ;

        Debug.DrawRay(this.transform.position, tankAngle * 10, Color.green, 2);
        Debug.DrawRay(this.transform.position, gasCanAngle, Color.red, 2);

        int clockwise = 1;
        if(GetCrossProduct(tankAngle, gasCanAngle).z < 0)
        {
            clockwise = -1;
        }

        float unityAngle = Vector3.SignedAngle(tankAngle, gasCanAngle, this.transform.forward);

        this.transform.Rotate(0,0,unityAngle);
    }

  

    Vector3 GetCrossProduct(Vector3 v, Vector3 w)
    {
        float xMult = v.y * w.z - v.z * w.y;
        float yMult = v.z * w.x - v.x * w.z;
        float zMult = v.x * w.y - v.y * w.x;

        Vector3 crossProd = new Vector3(xMult, yMult, zMult);

        return crossProd;

    }

    //---------------------------------------------------------
    //**********useful functions for ai and movement***********
    //******************************************
    //using AI, rotate gameobject toward a target/// pass in the vector 3 of two game objects 
    void rotateToTarget(GameObject targetObject)
    {
        Vector3 whoIslooking = this.transform.up;
        Vector3 targetObjectAngle = targetObject.transform.position - this.transform.position; 
        float unityAngle = Vector3.SignedAngle(whoIslooking, targetObjectAngle, this.transform.forward);

        this.transform.Rotate(0, 0, unityAngle);
    }
    //---------------------------------------------------
    //----------------------------------------------
    //*********calculate the distance to an object***********
    //********* returns a float of the distance between this game object and a target object
    float distanceToTarget(GameObject targetObject)
    {
        return Vector3.Distance(this.transform.position, targetObject.transform.position);
    }
    //-----------------------------------------------------------------
    //----------------------------------------------------------------
    //*******************Use AI to rotate to a target and move there******
    //**** not very good yet doesnt account for obstacles etc, 
    //uses a speed float var
    void AutoPilot(float autoPilotSpeed, GameObject targetGameObject)
    {
        rotateToTarget(targetGameObject);
        this.transform.Translate(this.transform.up * autoPilotSpeed, Space.World);

    }


    void Update()
    {
        // Get the horizontal and vertical axis.
        // By default they are mapped to the arrow keys.
        // The value is in the range -1 to 1
        float translation = Input.GetAxis("Vertical") * speed;
        float rotation = Input.GetAxis("Horizontal") * rotationSpeed;

        // Make it move in meters per second instead of meters per frame...
        translation *= Time.deltaTime;
        rotation *= Time.deltaTime;

        // Move translation along the object's z-axis
        transform.Translate(0, translation, 0);

        // Rotate around our y-axis
        transform.Rotate(0, 0, -rotation);

        if (Input.GetKeyDown(KeyCode.Space))
        {
            CalculateDistance();
            CalculateAngle();
        }

        if (Input.GetKeyDown(KeyCode.R))
        {
            rotateToTarget(gasCan);
            Debug.Log("Rotating to face " + gasCan.name);
        }

        if (Input.GetKeyDown(KeyCode.D))
        {
            Debug.Log("Deedubs distance: " + distanceToTarget(gasCan));
        }

        if (Input.GetKeyDown(KeyCode.P))
        {
            autoPilotMode = !autoPilotMode;
            if (autoPilotMode) AutoPilot(autoPilotSpeed, gasCan);
        }


    }
}

Full screen canvas overlay in Unity

There are many great uses for a full screen overlay. You can add splash screens, user interface elements and other features. Here is how to add a full screen overlay to your Unity Project.


To start with go ahead and create an Image GameObject.

In your hierarchy, right click and choose ui->Image.

This will add the Image Game Object as well as the Canvas as its parent. An EventSystem is also added.

To get a good view of the new Canvas Image element, make sure to enter 2D mode. Then you should select the Canvas GameObject in the Hierarchy, then place your cursor over the Scene and press F. Use zoom and scrolling to get your comfortable workspace settings.

Depending on your project you may want to take a look at the EventSystem GameObject. There are components attached to it which enable user interaction with any UI elements you might add to the project. If this does not apply to your project, you are free to delete the object from the hierarchy.

Looking at the inspector on the Canvas GameObject, the Canvas component has a RenderMode that should be set to the default of ScreenSpace – Overlay. This will stretch the image across the screen and ensure it is on top of any other content.

Screen Space - Overlay, where the Canvas fills the screen and all the UI elements of the canvas are rendered on top of everything else

There are two other components on the Canvas object: the Canvas Scaler and the Graphic Raycaster. The Canvas Scaler is a way of controlling the relative sizes of the UI elements when they are displayed on various screen sizes. The Graphic Raycaster is used to detect UI events. For example, when it detects a click, not only will it determine which UI element was clicked on, it will send the event to that element to be handled by the appropriate component.

We don’t need those two components for this project, so feel free to remove them from the Canvas GameObject.

Now we need to configure the Rect Transform component:

1. Make sure that the Image GameObject is selected in the Hierarchy window.

2. Find the Rect Transform component in the Inspector, then expand the Anchors setting.

3. Set the minimum values for x and y to 0. Set the maximum values for x and y to 1.

Now that the Anchor area of the Image is the whole screen, we no longer need an offset. Make sure to set the Left, Top, Right and Bottom properties to 0 on the Image’s Rect Transform

Your image now covers the entire screen and will stretch and move as needed depending on the screen size of the user’s device. I look forward to seeing what can be done with this, from start screens, end screens, custom user interfaces and more!

Unity Junior Programmer Mission Create With code Challenge 3 – Physics

In this challenge I was tasked to apply my knowledge of physics, scrolling backgrounds, and special effects to a balloon floating through town. The balloon must pick up tokens while avoiding explosions. I had to do a lot of troubleshooting in this project because it was riddled with errors. 

Upon successfully  completing this challenge I became proficient in application scripting , debugging, diagnosing and fixing code. I also practiced resolving compilation errors and fixing the cause of an exception.

https://meta.dwdenney.com/balloonfloat/

Whack A Food 2D Game

Image of coding environment  featuring Unity and Visual Studio
Working in Unity with Visual Studio Integration Development Environment

In this Unity learning challenge I put my User Interface skills to the test with this whack-a-mole-like challenge in which you have to get all the food that pops up on a grid while avoiding the skulls. I was required to debug buttons, mouse clicks, score tracking, restart sequences, and difficulty setting to get to the bottom of this one. I tested the  application, made a log of any errors/bugs in the code and gameplay. Using C# scripting and  utilizing various Unity APIs, I completed the debugging, diagnosing and fixing code that compiles but fails to perform as expected.

Challenge Outcome:

  • All of the buttons look nice with their text properly aligned
  • When you select a difficulty, the spawn rate changes accordingly
  • When you click a food, it is destroyed and the score is updated in the top-left
  • When you lose the game, a restart button appears that lets you play again

https://meta.dwdenney.com/whackafood/

3D Metaverse Script, Sculpt, Model and Design

I have a wide variety of Metaverse scripting skills, as well as 3D sculpting, modeling and design. Please check out the samples.

I have certifications in 3D sculpting, modeling and animation using 3D Studio Max. I also have skills using Unity, Blender, True Space 3D, Maya, Poser and Bryce

Upgrading a Website from Legacy to Web 2.0

The IT team that is quietly powering the entire Skagit Valley College information infrastructure is a talented team of Technology Specialists. This diverse group of enthusiastic developers has helped redefine the way technology is used and have dramatically impacted the future of web development. We were laughing about how small the website looked in the screens of the new large monitors. I mentioned hearing about a flexible website layout that would allow to better use the screen space. My leaders asked me to put together some information about the subject.

I began with the initial research of web frameworks and responsive web technology, and then I presented my findings to the web team. From there we decided to go with a responsive web site rather than creating a separate mobile site. The technology that we have put in to place can now detect a user’s screen size, and then “respond” by changing the web page to best fit the user’s devices from PC to smart TV to iPhones and beyond.

The previous site was built at a fixed size for the monitors of the day.

Skagit Valley College website 2011

The new design looked great on desktop computers as well as mobile devices.

Skagit Valley College website 2014
SVC website in responsive mode on mobile device