Hey guys and gals,
I am new to unity and I decided to make a simple game where you shoot marbles out of a canon. The canon is suppose to move back and fourth between two poles that show the boundaries of the level. The canon changes direction when it collides with the poles. At first I could not get it to work because I had to check “isKinematic” on the canon to keep it from falling. at which point collision stopped working. I solved this by placing a platform off camera that the canon could fall on which meant I could uncheck “isKinematic” and collision began working. After the user clicks LMB the canon stops going between the poles and should begin rotating left to right in an arc (i will figure out how to limit rotation later). I got the rotation to work … IF I make it “isKinematic” which disables my collision, if I don’t make it “isKinematic” it attempts to rotate but the platform below the canon collides with it and wont allow it to rotate more that a couple pixels. How would I go about getting both to work together?
Here is my code: C#
using UnityEngine;
using System.Collections;
public class CanonController : MonoBehaviour
{
//public float speed = 1.0f;
//public bool directionRight = false; //Gives the direction of the cannon movement. A value of True moves right, False moves left
private string direction = "right";
/**
* cannonState
* 1:moving left to right
* 2:rotating left to right along a arc
* 3:sits idle while marble is in motion
* */
public int canonState = 1;
// Update is called once per frame
void Update ()
{
if(Input.GetButtonDown("Fire1") canonState == 1)
{
canonState = 2;
}
else if(Input.GetButtonDown("Fire1") canonState == 2)
{
canonState = 1;
}
controlCanon();
}
void controlCanon() // controls the state of the cannon
{
if(canonState == 1)
{
moveState1();
}
if(canonState == 2)
{
moveState2();
}
if(canonState == 3)
{
// do nothing
}
}
void moveState1()// moves canon left and right while in state 1
{
if(direction == "right")//directionRight == true)
{
transform.Translate(Vector2.right *Time.deltaTime);
}
else
{
transform.Translate(Vector2.right * -1 * Time.deltaTime);
}
}
void moveState2()
{
transform.Rotate(0,0,2);
}
private void changeDirection() // changes direction of canon in state 1
{
if(direction == "right")//directionRight)
{
//directionRight = false;
direction = "left";
}
else
{
direction = "right";//directionRight = true;
}
}
void OnCollisionEnter2D(Collision2D collision)
{
changeDirection();
}
}