Make cube follow character five steps behind unity - unity3d

At the moment I have a script which when you hit a cube, it follows the player...but when you stand still it overlaps you. What I want is to be able to set the position of the cube to five steps behind the player at all times...how would i do this?
GameObject.Find("Cube2").transform.position = Vector3(0.5, 0.5, 0.5);
That is what I have tried so far, but that just makes the cube disappear?
the script in its entirety:
static var target : Transform; //the enemy's target
var moveSpeed = 3; //move speed
var rotationSpeed = 3; //speed of turning
var Player = GameObject.Find("Player").transform.position;
var Cube2 = GameObject.Find("Cube2").transform.position;
var myTransform : Transform; //current transform data of this enemy
function Awake()
{
//myTransform = transform; //cache transform data for easy access/preformance
}
function Start()
{
//target = GameObject.FindWithTag("Player1").transform; //target the player
}
//var distance = Vector3.Distance(Player.transform.position, Cube2.transform.position);
//Debug.Log(distance);
function Update () {
Debug.Log(Player);
//var distance = Vector3.Distance(Player.transform.position, Cube2.transform.position);
//var distance = Vector3.Distance(player_distance, cube_distance);
// if (distance > 5)
// {
if (target == GameObject.FindWithTag("Player").transform)
{
//rotate to look at the player
GameObject.Find("Cube2").transform.position = Vector3(0.5, 0.5, 0.5);
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
//move towards the player
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
//}
}

Like I said, I don't know unity really (had a 5 minute play with it)
In honesty it looks like you've pretty much got it - not sure why you can't get it working:
This is what should work: (assuming the quarternion calls are correct) - this is using latest Unity reference from the site so it might be diff to what works for you (what version of Unity you on?)
// Params
var moveSpeed = 3; // Move speed
var rotationSpeed = 3; // Speed of turning
// Find game objects
var Player = GameObject.Find("Player");
var Cube2 = GameObject.Find("Cube2");
function Update ()
{
// Vector from cube pos to player pos (vector math: target - position = vector to target from pos)
var dir = Player.transform.position - Cube2.transform.position;
// If the distance is over 5 units
if(dir.magnitude > 5.0f)
{
// Rotate towards player
Cube2.transform.rotation = Quaternion.Slerp(Cube2.transform.rotation, Quaternion.LookRotation(dir), rotationSpeed * Time.deltaTime);
// Move forward at specified speed
Cube2.transform.position += Cube2.transform.forward * moveSpeed * Time.deltaTime;
}
}
That should do it - if not let me know what happens (or if you get compilation errors) - like I said I don't really know Unity but I've had a look and I'm familiar with 3D/game programming

Related

Unity: Adding impulse to a ball from a certain position

I'm making a 3d pool game and I stuck with this problem.
I can't find the needed function to add an impulse to a ball which will make the ball to spin.
In other words, how to set the AIM point from where I want to add the impulse?
If I use AddForce or AddTorque, it seems that it calculates it from the Center of the Ball.
But how to specify the aim point (Left english, Right english, etc...)?
And how to route the ball to the camera direction after a cue hit the ball?
At first look I think you should check Rigidbody.AddForceAtPosition. You should calculate the aim points somehow in world coordinates also.
I am relatively new on Unity but the main idea came to my mind first rotate the cue vector by y axis by a small amount angle, then calculate the hit point for each regions by casting physics ray then finally apply impulse by using Rigidbody.AddForceAtPosition. I tried to write a sample code:
public class SphereController : MonoBehaviour {
private Vector3 cueStartPoint;
void Start () {
cueStartPoint = new Vector3(0, 0.5f, -13f);
}
void Update () {
//direction from cue to center
var direction = transform.position - cueStartPoint;
//rotate cue to aim right english
var angleForRightEnglish = 5f;
var directionForRight = Quaternion.AngleAxis(angleForRightEnglish, Vector3.up) * direction;
Debug.DrawRay(cueStartPoint, directionForRight, Color.red, 10f);
//rotate cue to aim right english
var angleForLeftEnglish = -5f;
var directionForLeft = Quaternion.AngleAxis(angleForLeftEnglish, Vector3.up) * direction;
Debug.DrawRay(cueStartPoint, directionForLeft, Color.blue, 10f);
//try a sample hit from right
if (Input.GetKeyDown(KeyCode.RightArrow)) {
var forceMagnitude = 1f;
var hitForce = forceMagnitude * directionForRight.normalized;
//calculate right hit point on sphere surface
RaycastHit hitInfo;
if (Physics.Raycast(cueStartPoint, directionForRight, out hitInfo)) {
var rightHitPoint = hitInfo.point;
gameObject.GetComponent<Rigidbody>().AddForceAtPosition(hitForce, rightHitPoint, ForceMode.Impulse);
}
}
//try a sample hit from left
if (Input.GetKeyDown(KeyCode.LeftArrow)) {
var forceMagnitude = 1f;
var hitForce = forceMagnitude * directionForLeft.normalized;
//calculate left hit point on sphere surface
RaycastHit hitInfo;
if (Physics.Raycast(cueStartPoint, directionForLeft, out hitInfo)) {
var leftHitPoint = hitInfo.point;
gameObject.GetComponent<Rigidbody>().AddForceAtPosition(hitForce, leftHitPoint, ForceMode.Impulse);
}
}
}
}
this script should be added to ball as component of course, hope this helps.

Enemy Ai unityscript movement issue

The code I am using currently makes the enemy notice me at a distance then follow me if I get closer. The issue I am having is with how they move. I am building a Minecraft style game but I cant get the enemies to stay on the ground and jump up each block like I have too with the fps controller. They just seem to float the shortest distance possible towards me.
Code:
var target : Transform; //the enemy's target
var moveSpeed = 3; //move speed
var rotationSpeed = 3; //speed of turning
var range : float=10f;
var range2 : float=10f;
var stop : float=0;
var myTransform : Transform; //current transform data of this enemy
function Awake()
{
myTransform = transform; //cache transform data for easy access/preformance
}
function Start()
{
target = GameObject.FindWithTag("1Player").transform; //target the player
}
function Update () {
//rotate to look at the player
var distance = Vector3.Distance(myTransform.position, target.position);
if (distance<=range2 && distance>=range){
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
}
else if(distance<=range && distance>stop){
//move towards the player
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
else if (distance<=stop) {
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
}
}
Okay now here is what you are missing:
1.Lock the rotation on x and z axis to zero
myTransform.eulerAngles = new Vector3(0f, myTransform.eulerAngles.y, 0);
Just add this line at the end.
2.Make a short distance raycast in front of the AI and if it detects some obstacle, stop the current movement and move by y axis, if there is no obstacle move like you wrote in your script.
As for the raycasting goes, there is no need for me to write it here, you can find more info about it in Unity3D documentation here:
http://docs.unity3d.com/ScriptReference/Physics.Raycast.html and this tutorial is good for staters: https://unity3d.com/learn/tutorials/modules/beginner/physics/raycasting

Move an object in unity2D towards another clicked object

I have an object called 'Player' in my scene.
I also have multiple objects called 'Trees'.
Now I'd like whenever the user clicks on a 'Tree', the 'Player' to move slowly to that position (using Lerp or moveTowards) is both O.K for me.
Now I have 2 issues with this code:
I'd like this code to be generic
Whenever I click a tree object I'd like this to move the player towards that tree. I don't want to write up this script and attach it to each tree object.
Where should I put the script?
Currently I attach this code to every tree object.
How should I write it down so that it applies to every tree object
in the scene?
If another click is made while moving, cancel previous movement and start moving to new position
How should I write it so that if I click on another object while the
player is moving towards another object that was clicked, the players stops moving towards it's previous position, and starts
moving towards the new point.
I'm having some trouble adjusting to the new UnityScript thingy. I come strictly from a Javascript background and it really seems like the 2 of them are languages with very different semantics. So if someone answers this with code(which is what I would want:) ), I'd appreciate some verbose comments as well.
I currently do this:
var playerIsMoving = false;
Public playerObject: Gameobject; //I drag in the editor the player in this public var
function update(){
var thisTreePosition = transform.point; //this store the X pos of the tree
var playerPosition = player.transform.point;
if(playerIsMoving){
player.transform.position = Vector2.MoveTowards(playerPosition, thisTreePosition, step);
}
}
function OnMouseDown(){
playerIsMoving = true;
}
I'm writing this from home where I don't have Unity and I forgot the code syntax therefore expect the above code to have typos or issues, at work it works just fine, apart from being very crude and unsophisticated.
I would recommend you to put the movement Script on the player. And how abour using Raycast to the test whether you hit a tree?
http://docs.unity3d.com/ScriptReference/Physics.Raycast.html
Vector3 positionToWalkTo = new Vector3();
void Update() {
if (Input.GetMouseButtonDown(0)) {
RaycastHit hit;
Ray ray = new Ray(transform.position, direction);
if (Physics.Raycast(ray, out hit))
if (hit.gameObject.tag.Equals("tree")){
positionToWalkTo = hit.gameObject.transform.position;
}
}
float step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, positionToWalkTo, step);
}
To get something like this running, you should tag all the trees.
'JavaScript'
var target: Transform;
// Speed in units per sec.
var speed: float;
function Update () {
if (Input.GetMouseButtonDown(0)) {
var hit: RaycastHit;
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
// Raycasting is like shooting something into the given direction (ray) and hit is the object which got hit
if (Physics.Raycast(ray, hit)) {
if (hit.gameObject.tag = "tree")
target = hit.gameObject.transform.position; // Sets the new target position
}
}
// The step size is equal to speed times frame time.
var step = speed * Time.deltaTime;
// Move our position a step closer to the target.
transform.position = Vector3.MoveTowards(transform.position, target.position, step);
}
Okay, so I've done it myself (with some help from Freshchris's answer).
Here it is:
var target:Vector2;
var targetObject:GameObject;
var initialY:float;
var tolerance = 1;
var speed = 3;
var isMoving = false;
function Start(){
target = transform.position;
}
function Update () {
if (Input.GetMouseButtonDown(0)) {
var hit: RaycastHit2D = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero); //raycast the scene
// if we hit something
if (hit.collider != null) {
isMoving=true; //it should start moving
targetObject = hit.collider.gameObject; //the target object
target = hit.collider.gameObject.transform.position;
}
}
// The step size is equal to speed times frame time.
var step = speed * Time.deltaTime;
// if it should be moving - move it - and face the player to the correct direction
if (isMoving){
if(transform.position.x>target.x){
gameObject.transform.localScale.x = -0.7;
}else {
gameObject.transform.localScale.x = 0.7;
}
transform.position = Vector2.MoveTowards(transform.position, target, step);
}
// if it reached the target object by a specified tolerance, tell it to stop moving
if(isMoving){
if((transform.position.x < target.x+tolerance)&&(transform.position.x > target.x-tolerance)){
print("position reached"); //this is fired just once since isMoving is switched to false just one line below
print(targetObject);
isMoving=false;
}
}
}

Falling through terrain everytime i crouch UNITY3d

in unity i made a script for my guy to crouch, run , and have his regular speed but when i crouch i just fall forever into the terrain was wondering if it is my code or i have to put a check on the terrain.
var walkSpeed: float = 7; // regular speed
var crchSpeed: float = 3; // crouching speed
var runSpeed: float = 20; // run speed
private var chMotor: CharacterMotor;
private var ch: CharacterController;
private var tr: Transform;
private var height: float; // initial height
function Start(){
chMotor = GetComponent(CharacterMotor);
tr = transform;
ch = GetComponent(CharacterController);
height = ch.height;
}
function Update(){
var h = height;
var speed = walkSpeed;
if (ch.isGrounded && Input.GetKey("left shift") || Input.GetKey("right shift")){
speed = runSpeed;
}
if (Input.GetKey("c")){ // press C to crouch
h = 0.5 * height;
speed = crchSpeed; // slow down when crouching
}
chMotor.movement.maxForwardSpeed = speed; // set max speed
var lastHeight = ch.height; // crouch/stand up smoothly
ch.height = Mathf.Lerp(ch.height, h, 5*Time.deltaTime);
tr.position.y += (ch.height-lastHeight)/2; // fix vertical position
}
This line could be responsible:
tr.position.y += (ch.height-lastHeight)/2;
you might want to let gravity take care of this or add a downward Force here. Changing the transform directly makes the Object dont care about colliders in the way.
edit: a better way would probably be to change the CharacterController though, as "falling down" when crouching doesnt make much sense. Maybe you dont even need this? The way i would implement this is the root at the feet, and height goes upwards from there.

Moving character left and right

Hello i followed a tutorial on how to make a top down shooter, the code makes so that my character rotates against my mouse and i can move forward and backwards using W and S. However i also want to be able to move right and left using A and D im not good when it comes to code in javascript nor unity3d i do most of my coding in c#. And the guy that made the tutorial explained poorly what some of the code actually do.
Here is the code:
#pragma strict
var speed : float = 20.0;
var rotateSpeed : float = 2.0;
function Update () {
var controller : CharacterController = GetComponent(CharacterController);
transform.Rotate(0,Input.GetAxis("Horizontal") * rotateSpeed,0);
var forward : Vector3 = transform.TransformDirection(Vector3.forward);
var curSpeed : float = speed * Input.GetAxis("Vertical");
controller.SimpleMove(forward * curSpeed);
var position = Input.mousePosition;
var newposition = Vector3(position.x,position.y,camera.main.transform.position.y- transform.position.y);
var lastposition = camera.main.ScreenToWorldPoint(newposition);
transform.LookAt(lastposition);
}
#script RequireComponent(CharacterController)
code for staffing (moving left and right without turning)
if(Input.GetKeyUp("d")){
controller.SimpleMove(right * staffingSpeed);
}
else if(Input.GetKeyUp("a")) {
controller.SimpleMove(-right * staffingSpeed);
}
write the code in update() function and make a variable "staffingSpeed" outside the function and set it from inspector
or
replace "staffingSpeed" with a constant numeric value e.g 5