Okay, I made some progress with the look towards me I'm able to get the enemy ship to follow the player and the laser guns as well could use some guidance how to get the laser to kill the player ship and prompt the lose and the 'R' for restart messages Aanty insight how to go about it is welcomed.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyManagement : MonoBehaviour
{
[SerializeField] GameObject deathFX;
[SerializeField] Transform parent;
// The target marker.
[SerializeField] Transform target;
// Angular speed in radians per sec.
[SerializeField] float speed;
// Start is called before the first frame update
void Start()
{
AddSphereCollider();
}
private void AddSphereCollider()
{
Collider sphereCollider = gameObject.AddComponent<SphereCollider>();
sphereCollider.isTrigger = false;
}
void Update()
{
Vector3 targetDir = target.position - transform.position;
// The step size is equal to speed times frame time.
float step = speed * Time.deltaTime;
Vector3 newDir = Vector3.RotateTowards(transform.forward, targetDir, step, 0.0f);
Debug.DrawRay(transform.position, newDir, Color.red);
// Move our position a step closer to the target.
transform.rotation = Quaternion.LookRotation(newDir);
}
}
You need to give it a radius for collision detection.
sphereCollider.radius = 10.0f;
Related
I am new at Unity/c# and I wanted to make a pong game. I made this by watching a tutorial on youtube. There is no "error" except the ball doesn't move after touching the player.
This is ball code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallCode : MonoBehaviour
{
private Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
Vector2 position = transform.position;
position.x = position.x - 5.8f * Time.deltaTime;
transform.position = position;
}
}
This is ball bounce code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallBounce : MonoBehaviour
{
private Rigidbody2D rb;
Vector3 lastVelocity;
// Start is called before the first frame update
void Awake()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
lastVelocity = rb.velocity;
}
private void OnCollisionEnter2D(Collision2D coll)
{
var speed = lastVelocity.magnitude;
var direction = Vector3.Reflect(lastVelocity.normalized, coll.contacts[0].normal);
}
}
And this is player code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public float moveSpeed = 4.5f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float vertical = Input.GetAxis("Vertical");
Vector2 position = transform.position;
position.y = position.y + moveSpeed * vertical * Time.deltaTime;
transform.position = position;
}
}
When I play the game the ball will collide with player, but it won't ricochet.
Your OnCollisionEnter2D method is not doing anything except set local variables that are quickly discarded. You need to make speed and direction variables of the BallCode or BallBounce class, then set up the BallCode class to use those variables in Update() when determining the motions it makes.
You can try adding a 2D rigid body property to the sphere and removing gravity.
Add a C# script to control the movement of the ball and add a 2D collider to the ball.
//Initial velocity
public float speed = 100f;
void Start()
{
this.GetComponent<Rigidbody2D>().AddForce
(Vector2.right * speed);
}
Add a 2D collider:
Add a 2D physical material to the sphere, so that the ball can bounce.
Modify 2D Physical Material Properties.
Added to the sphere's material.
Add player (Square) and control player movement script.
void Update()
{
// The mouse moves with the player
float y = Camer.main.ScreenToWorldPoint
(Input.mousePosition).y
this.transform.position = new Vector3
(transform.position.x,y,0);
}
Add the wall around the screen and the script Wall to control the randomness of the vertical speed and the direction of the ball when the ball collides with the wall.
public class Wall : MonoBehaviour
{
//Initial velocity
public float speed = 100f;
// Triggered when the collision ends
private void OnCollisionExit(Collision2D collision)
{
int r = 1;
if(Random.Range(0, 2) != -1)
{
r *= -1;
}
//add a vertical force
collision.gameObject.GetComponent<Rigidbody2D>().
AddForce(Vector2.up.*speed*r);
}
}
achieve effect:
I'm making a 2d open world game with physics similar to that of stardew valley, but for some reason there's a lot of input lag on the character even when I remove all the other scripts and animations.
I even tried removing most of the sprites such as houses and whatnot but it still has a lot of lag, not framerate lag, just the player movement.
I will attempt to explain: If you just lightly tap the keyboard the player moves and stops just fine, but if you hold down the button then let go (for about 5s gives the most lag, doesn't get any worse after that), the player keeps moving a little after you let go of the key.
Here's the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovementControls : MonoBehaviour {
public float speed;
private Vector2 MoveSpeed;
private Rigidbody2D Player;
void Start() {
Player = GetComponent<Rigidbody2D>();
}
void Update() {
Vector2 PlayerInput = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
MoveSpeed = PlayerInput.normalized * speed;
}
void FixedUpdate() {
Player.MovePosition(Player.position + MoveSpeed * Time.fixedDeltaTime);
}
}
Anyone know how to fix this?
Here's what fixed the problem to anyone else with said problem:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovementControls : MonoBehaviour {
public float speed; //Change the player's speed
private Vector2 MoveSpeed; //This is what the player's speed will be set to after some math
private Rigidbody2D Player; //The player
void Start() {
Player = GetComponent<Rigidbody2D>(); //Find the player GameObject
}
void Update() {
Vector2 PlayerInput = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")); //Get input
MoveSpeed = PlayerInput * speed; //Math
Player.MovePosition(Player.position + MoveSpeed * Time.fixedDeltaTime); //Move the player
}
}
I am making the enemy character to follow the player character.
In the FixedUpdate method the enemy character move toward the player character,
then in the Update method character rotates to the player character.
However, with this script, somehow enemy character is just nudging and gets stuck.
Where is the mistake, what's wrong???
public class enemy : MonoBehaviour
{
GameObject tObj;
private Vector3 latestPos;
public string targetObjectName;
public float speed = (float)1.0;
void Start()
{
tObj = GameObject.Find("player");
latestPos = transform.position;
}
void Update()
{
Vector3 diff = transform.position - latestPos;
latestPos = transform.position;
if (diff.magnitude > 0.01f)
{
transform.rotation = Quaternion.LookRotation(diff);
}
}
void FixedUpdate(){
Vector3 dir = (tObj.transform.position - this.transform.position).normalized;
float vx = dir.x * speed;
float vz = dir.z * speed;
this.transform.Translate((float)(vx / 50.0),0,(float)(vz / 50.0));
}
}
Use Package Manager "Standard Assets", Inside Unity put two FPSController one should be Player and the second can be Enemy.
I know this does not answers your question but its a faster way to ad Enemy.
AI Settings
Just remove the camera, Audio Source and First Person Controller Script as in image.
The Code for AI:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FollowAI : MonoBehaviour
{
public CharacterController _controller;
public Transform target;
public GameObject Player;
[SerializeField]
float _moveSpeed = 2.0f;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update() {
Vector3 direction = target.position - transform.position;
direction = direction.normalized;
Vector3 velocity = direction * _moveSpeed;
_controller.Move(velocity * Time.deltaTime);
Vector3 lookVector = Player.transform.position - transform.position;
lookVector.y = transform.position.y;
Quaternion rot = Quaternion.LookRotation(lookVector);
transform.rotation = Quaternion.Slerp(transform.rotation, rot, 1);
}
}
I'm a total newbie in Unity and I'm learning/making my first game, which will be a platformer. I want to get the movement perfect first. I've added a simple script that enables the player to move and jump.
Here it is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour{
public float jumpspeed = 5f;
public float speed = 5f;
Rigidbody2D rb;
GameObject character;
// Start is called before the first frame update
void Start()
{
}
void Awake(){
rb = gameObject.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space)){
Jump();
}
Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0f, 0f);
transform.position += move *Time.deltaTime * speed;
}
void Jump(){
rb.AddForce(new Vector2(0f, jumpspeed), ForceMode2D.Impulse);
}
}
Now, I want the character to face in the direction in which it moves. The png is facing to the right by default.
How can I do that? Also, can I make my movement script better?
Thanks in advance!
I typically do this using code like this based off a bool.
void FlipSprite()
{
isFacingRight = !isFacingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
I used This code for my MainCamera for following the player in my 2d game in Unity5 :
using UnityEngine;
using System.Collections;
public class CameraFollow : MonoBehaviour {
public float dampTime = 0.15f;
private Vector3 velocity = Vector3.zero;
public Transform target;
// Update is called once per frame
void Update ()
{
if (target)
{
Vector3 point = GetComponent<Camera>().WorldToViewportPoint(target.position);
Vector3 delta = target.position - GetComponent<Camera>().ViewportToWorldPoint(new Vector3(0.5f, 0.5f, point.z)); //(new Vector3(0.5, 0.5, point.z));
Vector3 destination = transform.position + delta;
transform.position = Vector3.SmoothDamp(transform.position, destination, ref velocity, dampTime);
}
}
}
It work fine But player is in middle of screen allways . i wan player be in down of screen and my sprite for show Earth of my game will stick below the camera . i mean better in following pictures:
What I Want :
The Result :
You can add a vertical offset to the calculation. Just adding it to destination should do that I think.
Vector3 destination = ...
destination.y += someOffset;
transform.position = Vector3.SmoothDamp(...);
Otherwise you could also add an empty gameobject to the player gameobject and use that as your target.
One thing that you might need to consider is the resolution.