SchultzGames
Para tirar dúvidas, crie um tópico especifico na área "Dúvidas em Geral" e aguarde ser respondido. Evite comentar em tópicos não relacionados a sua dúvida :D
TÓPICOS RECENTES:
Tópico:
Postado em:
Postado por:
ShapeKeys do Blender para a Unity altera áreas próximas
COMO EVITAR QUE UM OBJETO (PLAYER,ITEM ETC...) ATRAVESSE UMA PAREDE.
Ajuda em Script de Verificação de Ação e Reação
unity Failed to load PlayerSettings (internal index #0). Most likely data f
modelar avatar e skins para um jogo web
PRECISO FAZER QUE MEU GAME FIQUE ONLINE
Materiais do Blander não aparecem no MeshRendere do Objeto na Unity
Repetiçoes de Textura no Terreno
SERVER IS DOWN - UNITY+MSQL
Procuro programadores - Novo jogo
Problema com o MS VEHICLES
Preciso de ajuda com a Unity
Problema com vídeo em 360° na Unity
Problemas no MS Vehicles
unity- eventos na Animação com Armature/Bones vinda do blender não funciona
ajuda exibir resultados simulados em uma liga Game Unity
Unity - ParticleSystem não é redirecionado no rawimage no canvas
Como resolver o problema de "face orientation" no Blender.
[DÚVIDA] Tive um problema com meu Canvas
erro na Directional Light
Problemas com o Directional Light da Unity 3D
210 Linhas de código para inimigo é muito grande?
Novo jogo da franquia Sphere game em desenvolvimento
malha da roda não girando com wheel collider unity
Problemas com ambiguidade
Touch mobile
INVALID TOKEN
Como acessar o "HD Render Pipeline" do HDRP por script?
CHAT GPT PRA JOGO DE TIRO? comentem
Tutorial script inimigo segue e foge do player
Ainda vale a pena lançar Asset na Asset Store?
Ajuda com tabela de historico de pontuaçao.
[TUTORIAL] Entrar no carro estilo GTA
Como derrapar um Whell Collider
Como altertar o valor do "Asymptote Value" do Whell Collider via Script
Preciso de ajuda para substituir valor de variavel em outro script
Ajuda com Top Down Shooter utilizando Photon
Duvida com Netcode
[RESOLVIDO] Unity - Movendo a Câmera na Horizontal/Vertical com Touch
Alguém me ajuda com os anúncios pfv
Segundo Trailer do jogo Dark Age, Feliz Natal a todos!
Unity - ScrollRect, Viewport, Content - O Conteúdo ñ inicia no topo
Coleta de itens
Unity - Cadastro do email do jogador
[GRATIS] PACK DE MODELOS 3D PARA JOGO DE TERROR
Onde Conseguir músicas para meu Jogo?
error CS0246 em Script
Alguem teve ja esse problema?
[Projeto em Andamento] Draug, um jogo de hordas
DISPONIVEL PARA FAZER MODELOS 3D
Unity-Loja.Como os Jogadores terão acesso aos ítens comprados na PlayStore?
Bugando depois do Build.
Primeiro Trailer do jogo Dark Age
Problema com sombra
Mesh e Material do objeto trocando para uma instancia no inicio do jogo
[RESOLVIDO] Unity - RawImages_Layer_Camera
INVESTIMENTO EM JOGOS E BANCO DE TALENTO
Teaser do meu novo projeto pessoal, Dark Age
Preciso de ajuda com mudança para mobile androide.
[RESOLVIDO] Posição final do objeto em jogo 2D
Input.GetAxis() obedercer a orientação de um objeto.
Interação com elementos UI
Meu primeiro jogo na steam
Minimap/Radar/GPS Estilo GTA V
[RESOLVIDO] Erro no console depois que formatei o pc
PACK GRÁTIS de Músicas ELETRÔNICAS para ajudar vocês em seus Jogos Indies!
[TUTORIAL] Entenda como funciona: ENUM, SWITCH, BREAK, CASE no C#
O Labirinto II - Baixe o Jogo
Qual e o codigo de Botões na unity para saber seus estados?
Como carregar itens pequenos dentro do carro sem que atravesse os colliders
[Duvida] Script pegar itens
Travamento ao trocar de cena
Colisão zoada e movimentação
Salvar objetos que foram destruidos entre cenas na unity
Quero começa a desenvolver um jogo de luta porem eu queria aprender a faze
Pegar qual objeto colidiu com o Linecast.
movimentação e camera?
[RESOLVIDO] Unity - SceneManager.LoadScene abre scene com objeto "vazio"
[RESOLVIDO] ajuda sobre skybox
MEU SIMULADOR DE CARRO
[_____IMPORTANTE_____] ALTERAÇÕES NA POLÍTICA DE COBRANÇA DA UNITY
[RESOLVIDO] Ausencia da funçao NavMesh na Unity 2022.2.12
[_____IMPORTANTE_____] ALTERAÇÕES NA POLÍTICA DE COBRANÇA DA UNITY - 2
Roll Up Um jogo de aventura e desáfios
Terminologia da Unity em outras engines
Como criar a iluminação do Sol no Sistema Solar?
Conexão de lobby pelo OnConnectedToMaster
Problema na exportção de projeto unity
[RESOLVIDO] Unity - Áudios estão emitindo som só Depois do Botão ser solto
Unity - Banco de Dados Online junto ao Jogo
Player virar para o inimigo(Prefab)
[TUTORIAL] Sistema De Save Game Ao Sair Da Fase
Problema de Sincronização de um objeto de um jogo multiplayer usa q Photon
Unity - Compartilhar meu Jogo
Alguém que manja do Google ADmob?
Unity - Avaliar meu Jogo
[RESOLVIDO] Destruir inimigo com o player.
Salvar e carregar dados na Unity de objetos prefabs sem sobrescrever os dad
Unity - Salvar os Dados do Jogador Online
Ontem à(s) 10:09 pm
Dom Mar 10, 2024 2:30 pm
Sex Mar 01, 2024 1:27 pm
Qui Fev 22, 2024 9:57 pm
Qua Fev 21, 2024 10:39 am
Ter Fev 20, 2024 9:28 am
Ter Fev 20, 2024 12:15 am
Seg Fev 19, 2024 1:06 pm
Seg Fev 12, 2024 1:56 pm
Seg Fev 12, 2024 1:17 pm
Dom Fev 11, 2024 8:55 pm
Dom Fev 11, 2024 11:16 am
Seg Fev 05, 2024 4:18 pm
Dom Fev 04, 2024 9:39 pm
Qua Jan 31, 2024 11:59 pm
Ter Jan 30, 2024 7:37 pm
Ter Jan 23, 2024 6:33 pm
Dom Jan 21, 2024 6:03 pm
Sáb Jan 20, 2024 7:03 pm
Sáb Jan 20, 2024 6:58 pm
Sáb Jan 20, 2024 6:39 pm
Sex Jan 19, 2024 1:29 pm
Sex Jan 19, 2024 8:40 am
Dom Jan 14, 2024 5:30 pm
Qua Jan 10, 2024 10:29 pm
Qua Jan 10, 2024 8:55 pm
Qua Jan 10, 2024 7:14 pm
Ter Jan 09, 2024 3:55 pm
Ter Jan 09, 2024 8:04 am
Sáb Jan 06, 2024 8:02 pm
Sex Jan 05, 2024 7:01 am
Sex Jan 05, 2024 12:12 am
Qui Jan 04, 2024 6:55 pm
Qui Jan 04, 2024 12:52 pm
Qui Jan 04, 2024 4:34 am
Ter Jan 02, 2024 11:48 pm
Dom Dez 31, 2023 7:25 pm
Qua Dez 27, 2023 5:44 pm
Qua Dez 27, 2023 3:08 pm
Sáb Dez 23, 2023 7:27 pm
Sáb Dez 23, 2023 5:06 pm
Qui Dez 21, 2023 8:10 pm
Seg Dez 18, 2023 2:04 pm
Sex Dez 15, 2023 5:11 pm
Qui Dez 14, 2023 9:13 pm
Qui Dez 14, 2023 2:47 pm
Qui Dez 14, 2023 1:48 pm
Qua Dez 13, 2023 8:58 pm
Ter Dez 12, 2023 2:32 pm
Seg Dez 11, 2023 1:53 pm
Qua Dez 06, 2023 8:13 pm
Sáb Dez 02, 2023 8:06 pm
Qui Nov 30, 2023 7:49 am
Seg Nov 27, 2023 1:35 am
Qua Nov 22, 2023 7:37 am
Qui Nov 09, 2023 1:22 pm
Seg Nov 06, 2023 11:59 am
Ter Out 31, 2023 9:53 am
Dom Out 29, 2023 8:05 pm
Dom Out 29, 2023 3:03 am
Sex Out 27, 2023 3:43 pm
Sex Out 27, 2023 3:28 pm
Qua Out 25, 2023 1:20 pm
Seg Out 23, 2023 10:34 am
Dom Out 22, 2023 6:55 pm
Qui Out 19, 2023 11:57 pm
Qui Out 19, 2023 6:39 pm
Ter Out 17, 2023 6:37 pm
Ter Out 17, 2023 6:18 pm
Seg Out 16, 2023 1:59 pm
Sáb Out 14, 2023 12:15 pm
Qua Out 11, 2023 6:07 pm
Seg Out 09, 2023 4:19 pm
Qua Out 04, 2023 12:12 pm
Qua Out 04, 2023 12:11 pm
Ter Out 03, 2023 9:18 pm
Ter Out 03, 2023 9:08 pm
Ter Out 03, 2023 6:05 pm
Ter Set 26, 2023 12:45 pm
Seg Set 25, 2023 9:02 pm
Seg Set 25, 2023 9:47 am
Sáb Set 23, 2023 2:10 pm
Sex Set 22, 2023 9:01 pm
Qui Set 21, 2023 11:04 am
Qua Set 20, 2023 4:40 pm
Qua Set 20, 2023 9:15 am
Dom Set 17, 2023 12:17 pm
Sex Set 15, 2023 7:24 pm
Sex Set 15, 2023 5:41 pm
Sex Set 15, 2023 4:28 pm
Sex Set 15, 2023 10:56 am
Sex Set 15, 2023 10:15 am
Seg Set 11, 2023 11:43 am
Seg Set 11, 2023 11:31 am
Sáb Set 09, 2023 4:53 pm
Sáb Set 09, 2023 1:44 pm
Ter Set 05, 2023 11:12 pm
Ter Set 05, 2023 3:12 pm
Seg Set 04, 2023 11:53 pm



































































































(Jogo De FPS) Código para tirar HP ao entrar em lugares não permitidos

3 participantes

Ir para baixo

DÚVIDA (Jogo De FPS) Código para tirar HP ao entrar em lugares não permitidos

Mensagem por Sheyk Sáb Jul 02, 2016 12:44 am

Olá galera bom dia a Todos (a)

Bom, Eu gostaria de saber como eu posso fazer para quando o player for para um lugares não permitidos no mapa (tentar Bugar ou sair por engano) como posso fazer para ele perder HP até morrer ?
Sheyk
Sheyk
Avançado
Avançado

PONTOS : 3105
REPUTAÇÃO : 27
Idade : 24
Respeito as regras : (Jogo De FPS) Código para tirar HP ao entrar em lugares não permitidos WvDYdlf

Ir para o topo Ir para baixo

DÚVIDA Re: (Jogo De FPS) Código para tirar HP ao entrar em lugares não permitidos

Mensagem por Sheyk Sáb Jul 02, 2016 7:02 am

Me ajudem por favor galera  :D
Sheyk
Sheyk
Avançado
Avançado

PONTOS : 3105
REPUTAÇÃO : 27
Idade : 24
Respeito as regras : (Jogo De FPS) Código para tirar HP ao entrar em lugares não permitidos WvDYdlf

Ir para o topo Ir para baixo

DÚVIDA Re: (Jogo De FPS) Código para tirar HP ao entrar em lugares não permitidos

Mensagem por JohnRambo Sáb Jul 02, 2016 8:58 am

Você já tentou?
JohnRambo
JohnRambo
Moderador

Masculino PONTOS : 4927
REPUTAÇÃO : 661
Idade : 23
Áreas de atuação : Unity;
Programação;
Música e Sonorização;
Graduado em Análise e Desenvolvimento de Sistemas;
Respeito as regras : (Jogo De FPS) Código para tirar HP ao entrar em lugares não permitidos Aad8pUi

Ir para o topo Ir para baixo

DÚVIDA Re: (Jogo De FPS) Código para tirar HP ao entrar em lugares não permitidos

Mensagem por Sheyk Sáb Jul 02, 2016 9:01 am

Sim, mais Eu só consegui fazer o Colíder invisível...
Mais eu não sei fazer para tirar HP do player
Sheyk
Sheyk
Avançado
Avançado

PONTOS : 3105
REPUTAÇÃO : 27
Idade : 24
Respeito as regras : (Jogo De FPS) Código para tirar HP ao entrar em lugares não permitidos WvDYdlf

Ir para o topo Ir para baixo

DÚVIDA Re: (Jogo De FPS) Código para tirar HP ao entrar em lugares não permitidos

Mensagem por JohnRambo Sáb Jul 02, 2016 9:04 am

OK... Se vc não tiver com pressa eu posso te dar uma ajuda daqui uns 90 minutos.. É que agora to um pouco ocupado
JohnRambo
JohnRambo
Moderador

Masculino PONTOS : 4927
REPUTAÇÃO : 661
Idade : 23
Áreas de atuação : Unity;
Programação;
Música e Sonorização;
Graduado em Análise e Desenvolvimento de Sistemas;
Respeito as regras : (Jogo De FPS) Código para tirar HP ao entrar em lugares não permitidos Aad8pUi

Ir para o topo Ir para baixo

DÚVIDA Re: (Jogo De FPS) Código para tirar HP ao entrar em lugares não permitidos

Mensagem por Sheyk Sáb Jul 02, 2016 9:06 am

Show, não estou com pressa não, hj vou fazer bastante coisas no meu jogo!!! :D
Sheyk
Sheyk
Avançado
Avançado

PONTOS : 3105
REPUTAÇÃO : 27
Idade : 24
Respeito as regras : (Jogo De FPS) Código para tirar HP ao entrar em lugares não permitidos WvDYdlf

Ir para o topo Ir para baixo

DÚVIDA Re: (Jogo De FPS) Código para tirar HP ao entrar em lugares não permitidos

Mensagem por JohnRambo Sáb Jul 02, 2016 10:10 am

OK preciso do script do seu player
JohnRambo
JohnRambo
Moderador

Masculino PONTOS : 4927
REPUTAÇÃO : 661
Idade : 23
Áreas de atuação : Unity;
Programação;
Música e Sonorização;
Graduado em Análise e Desenvolvimento de Sistemas;
Respeito as regras : (Jogo De FPS) Código para tirar HP ao entrar em lugares não permitidos Aad8pUi

Ir para o topo Ir para baixo

DÚVIDA Re: (Jogo De FPS) Código para tirar HP ao entrar em lugares não permitidos

Mensagem por Sheyk Sáb Jul 02, 2016 10:24 am

//New FPS
//@2016

using UnityEngine;
using System.Collections;
using Hashtable = ExitGames.Client.Photon.Hashtable; //Replace default Hashtables with Photon hashtables

public class PlayerNetwork : Photon.MonoBehaviour
{

//This is main script that coordinate our player in game, it decides which component to enable/disable
//Also it sync's our data with remote instances over network

public SoldierAnimation soldierAnimation;
public Renderer soldierBody;
public Material teamALook;
public Material teamBLook;
public Material fpsHandMaterial;
public PlayerWeapons playerWeapons;
public GameObject firstPersonView;

public Transform nameLabelTransform;
public GUIText nameLabel;
public GUIText nameLabelShadow;

public AudioSource playerAudio;
public AudioSource walkingAudio;

public AudioClip hitSound;
public AudioClip[] walkingSounds;
public AudioClip[] ladderSounds;

public Collider[] headHitBoxes;
public Collider[] torsoHitBoxes;
public Collider[] limbsHitBoxes;

Vector3 playerPos = Vector3.zero;
[HideInInspector]
public Vector3 aimPos = Vector3.zero;
Vector3 smoothAimPos = Vector3.zero;
float positionSmoother = 17.5f;
float d;

[HideInInspector]
public FPSController fpsController;
FPSMouseLook localMouseLook;
[HideInInspector]
public FPSMouseLook cameraMouseLook;
[HideInInspector]
public Transform thisT;
//[HideInInspector]
//public RoomController rc;
[HideInInspector]
public int playerID;
[HideInInspector]
public bool playerKilled = false;

int currentWeaponIndex = -1;
int previousWeaponIndex = -1;
bool isFiringRemote = false;
int playerTeam;
Camera mainCamera;
Transform mainCameraT;
Vector3 screenPos; //For name label display
float offset;
//Save references incase we kill this player
string lastWeaponName = "";
int lastBodyPart = -1;

//Position Interpolation Sync
double interpolationBackTime = 0.37d; 

internal struct State
    {
internal double timestamp;
internal Vector3 pos;
internal Quaternion rot;
}

//double currentTime;

// We store twenty states with "playback" information
State[] m_BufferedState = new State[20];
// Keep track of what slots are used
int m_TimestampCount;
int movementStateLocal = -1;
int receivedMovementState = -1;
float stepLength; //Used for playing walking sounds

// Use this for initialization
void Start ()
    {
photonView.synchronization = ViewSynchronization.Unreliable;

localMouseLook = GetComponent<FPSMouseLook>();
fpsController = GetComponent<FPSController>();
fpsController.pn = this;

playerWeapons.playerNetwork = this;
playerWeapons.soldierAnimation = soldierAnimation;
playerWeapons.fpsController = fpsController;
playerWeapons.QuickSetup(photonView.isMine);

gameObject.name = photonView.owner.name;
thisT = transform;

playerKilled = false;

gameObject.layer = 2; //Set layer to Ignore Raycast

if(!photonView.isMine)
        {
//Deactivate all scripts and object that are not used by remote instance
localMouseLook.enabled = false;
fpsController.enabled = false;
playerWeapons.enabled = false;
firstPersonView.SetActive(false);
if(!soldierAnimation.gameObject.activeSelf)
            {
soldierAnimation.gameObject.SetActive(true);
}
soldierAnimation.playerWeapons = playerWeapons;
soldierAnimation.playerNetwork = this;
soldierAnimation.Setup();

SetupBoxes(headHitBoxes, HitBox.BodyPart.Head);
SetupBoxes(torsoHitBoxes, HitBox.BodyPart.Torso);
SetupBoxes(limbsHitBoxes, HitBox.BodyPart.Limbs);

//Add this player to reference
GameSettings.rc.otherPlayers.Add(this);
}
        else
        {
firstPersonView.SetActive(true);
soldierAnimation.gameObject.SetActive(false);
cameraMouseLook = playerWeapons.playerCamera.GetComponent<FPSMouseLook>();
nameLabelTransform.gameObject.SetActive(false);
gameObject.tag = "Player";
}

if(PhotonNetwork.isMasterClient)
        {
//Set player HP
Hashtable setPlayerData = new Hashtable();
setPlayerData.Add("PlayerHP", (int)100);
photonView.owner.SetCustomProperties(setPlayerData);
}

playerTeam = (int)photonView.owner.customProperties["Team"];
playerID = photonView.owner.ID;

if(playerTeam == 1 || playerTeam == 2)
        {
if(playerTeam == 1)
            {
soldierBody.sharedMaterial = teamALook;
}
            else
            {
soldierBody.sharedMaterial = teamBLook;
}

if(photonView.isMine)
            {
fpsHandMaterial.SetTexture("_MainTex", soldierBody.sharedMaterial.GetTexture("_MainTex"));
fpsHandMaterial.color = soldierBody.sharedMaterial.color;
}
            else
            {
nameLabel.text = photonView.name;
nameLabelShadow.text = photonView.name;
nameLabel.color = playerTeam == 1 ? GameSettings.teamAColor : GameSettings.teamBColor;
}
}
}

void SetupBoxes (Collider[] tmpBoxes, HitBox.BodyPart bp)
    {
for(int i = 0; i < tmpBoxes.Length; i++)
        {
tmpBoxes[i].isTrigger = true;
tmpBoxes[i].gameObject.AddComponent tmpBoxes[i].tag = "Body";
}
}

//Sync player over network
void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
    {
if (stream.isWriting)
        {
//Send data
if(!thisT)
return;

stream.SendNext(thisT.position);
stream.SendNext(playerWeapons.playerCamera.position + playerWeapons.playerCamera.forward * 100);
stream.SendNext(playerWeapons.globalWeaponIndex);
stream.SendNext(playerWeapons.isFiring);
stream.SendNext(fpsController.movementState);
}
        else
        {
//Receive data
playerPos = (Vector3)stream.ReceiveNext();
aimPos = (Vector3)stream.ReceiveNext();
currentWeaponIndex = (int)stream.ReceiveNext();
isFiringRemote = (bool)stream.ReceiveNext();
soldierAnimation.movementState = (int)stream.ReceiveNext();


// Shift buffer contents, oldest data erased, 18 becomes 19, ... , 0 becomes 1
for (int i=m_BufferedState.Length-1;i>=1;i--)
{
m_BufferedState[i] = m_BufferedState[i-1];
}

// Save currect received state as 0 in the buffer, safe to overwrite after shifting
State state = new State();
state.timestamp = info.timestamp;
state.pos = playerPos;
http://state.rot = rot;
m_BufferedState[0] = state;

// Increment state count but never exceed buffer size
m_TimestampCount = Mathf.Min(m_TimestampCount + 1, m_BufferedState.Length);

// Check integrity, lowest numbered state in the buffer is newest and so on
for (int i=0;i<m_TimestampCount-1;i++)
{
if (m_BufferedState[i].timestamp < m_BufferedState[i+1].timestamp)
Debug.Log("State inconsistent");
}
}
}

// Update is called once per frame
void Update ()
    {
if(!photonView.isMine)
        {
InterpolatePosition ();

smoothAimPos = Vector3.Lerp(smoothAimPos, aimPos, Time.deltaTime * positionSmoother);

if(aimPos != Vector3.zero)
            {
thisT.LookAt(new Vector3(smoothAimPos.x, thisT.position.y, smoothAimPos.z));
playerWeapons.playerCamera.LookAt(smoothAimPos);
}

if(isFiringRemote)
            {
playerWeapons.FireRemote();
}

if(previousWeaponIndex != currentWeaponIndex)
            {
previousWeaponIndex = currentWeaponIndex;
playerWeapons.globalWeaponIndex = currentWeaponIndex;
playerWeapons.SwitchWeaponRemote();
}

//Show name label for our teammates
if(!playerKilled && ((playerTeam == GameSettings.ourTeam && GameSettings.currentGameMode != "FFA") || GameSettings.ourTeam == 0))
            {
if(!nameLabelTransform.gameObject.activeSelf)
                {
nameLabelTransform.gameObject.SetActive(true);
}

if(!mainCamera || !mainCamera.gameObject.activeInHierarchy)
                {
if(Camera.main)
                    {
mainCamera = Camera.main;
mainCameraT = mainCamera.transform;
}
}
                else
                {
offset = Vector3.Distance(mainCameraT.position, thisT.position)/50;
screenPos = mainCamera.WorldToViewportPoint(new Vector3(thisT.position.x, thisT.position.y + 2.6f + offset, thisT.position.z));

if(screenPos.z > 0)
                    {
nameLabelTransform.position = new Vector3(screenPos.x, screenPos.y);
}
                    else
                    {
nameLabelTransform.position = new Vector3(-350, -350);
}
}

nameLabelTransform.eulerAngles = Vector3.zero;
}
            else
            {
if(nameLabelTransform.gameObject.activeSelf)
                {
nameLabelTransform.gameObject.SetActive(false);
}
}

receivedMovementState = soldierAnimation.movementState;
}
        else
        {
//Send cameraFOV to reduce mouse sensitivity when aiming
http://localMouseLook.cameraFOV = playerWeapons.mainPlayerCamera.fieldOfView;
http://cameraMouseLook.cameraFOV = playerWeapons.mainPlayerCamera.fieldOfView;

receivedMovementState = fpsController.movementState;
}

//Play footstep sound for both local and remote player instances
if(!playerKilled)
        {
if(movementStateLocal != receivedMovementState)
            {
movementStateLocal = receivedMovementState;
PlayWalkingSound();
}
}
        else
        {
if(walkingAudio.isPlaying)
            {
walkingAudio.Stop();
}
}
}

void InterpolatePosition ()
    {
d = Vector3.Distance(thisT.position, m_BufferedState[0].pos);
soldierAnimation.isMoving = d > 0.1f;

double currentTime = PhotonNetwork.time;
double interpolationTime = currentTime - interpolationBackTime;
// We have a window of interpolationBackTime where we basically play 
// By having interpolationBackTime the average ping, you will usually use interpolation.
// And only if no more data arrives we will use extrapolation

// Use interpolation
// Check if latest state exceeds interpolation time, if this is the case then
// it is too old and extrapolation should be used

if (m_BufferedState[0].timestamp > interpolationTime)
        {
for (int i=0;i<m_TimestampCount;i++)
            {
// Find the state which matches the interpolation time (time+0.1) or use last state
if (m_BufferedState[i].timestamp <= interpolationTime || i == m_TimestampCount-1)
                {
// The state one slot newer (<100ms) than the best playback state
State rhs = m_BufferedState[Mathf.Max(i-1, 0)];
// The best playback state (closest to 100 ms old (default time))
State lhs = m_BufferedState[i];

// Use the time between the two slots to determine if interpolation is necessary
double length = rhs.timestamp - lhs.timestamp;
float t = 0.0F;
// As the time difference gets closer to 100 ms t gets closer to 1 in 
// which case rhs is only used
if (length > 0.0001)
                    {
t = (float)((interpolationTime - lhs.timestamp) / length);
}

// if t=0 => lhs is used directly
thisT.position = Vector3.Lerp(lhs.pos, rhs.pos, t);
http://transform.localRotation = Quaternion.Slerp(lhs.rot, rhs.rot, t);
return;
}
}
}
        else
        {
// Use extrapolation. Here we do something really simple and just repeat the last
// received state. You can do clever stuff with predicting what should happen

State latest = m_BufferedState[0];

thisT.position = latest.pos;
http://transform.localRotation = latest.rot;

//print ("Moving DIrectly to latest pos " + Random.Range(111, 333).ToString());
}
}

//Called from Weapon.cs when player shooting single fire weapons
public void FireSingleRemote()
    {
photonView.RPC("FireRemoteRPC", PhotonTargets.Others);
}

[PunRPC]
void FireRemoteRPC()
    {
playerWeapons.FireRemote();
}

//Reload Sync
public void DoReload ()
    {
photonView.RPC("DoReloadRemote", PhotonTargets.Others);
}

[PunRPC]
void DoReloadRemote()
    {
if(playerWeapons.currentSelectedWeapon)
        {
playerWeapons.currentSelectedWeapon.ReloadNetworkSync();
}
}

//Do player damage, called from HitBox.cs
public void ApplyDamage(int[] values)
    {
if(!playerKilled && (playerTeam != GameSettings.ourTeam || photonView.isMine || GameSettings.currentGameMode == "FFA"))
        {
photonView.RPC("DamageRemote", PhotonTargets.All, values, PhotonNetwork.player.ID);
}
}

[PunRPC]
void DamageRemote (int[] values, int killerID)
    {
if(photonView.isMine)
        {
GameSettings.rc.DoHitDetector((int)values[2]);
fpsController.fallSlowDown = 0.5f;

PlayHitSound();
}
        else
        {
soldierAnimation.DoHitMovement();
}

if(!playerKilled)
        {
if(PhotonNetwork.player.ID == killerID)
            {
//Save temp references
lastWeaponName = GameSettings.rc.ourPlayer ? GameSettings.rc.ourPlayer.playerWeapons.currentSelectedWeapon.weaponName : "";
lastBodyPart = values[1];
}

if(PhotonNetwork.isMasterClient)
            {
int currentHP = photonView.owner.customProperties["PlayerHP"] != null ? (int)photonView.owner.customProperties["PlayerHP"] : 100;
currentHP -= GetDMG((int)values[0], (int)values[1]);
Hashtable setPlayerData = new Hashtable();
setPlayerData.Add("PlayerHP", currentHP); //Setup player HP by master client
photonView.owner.SetCustomProperties(setPlayerData);

if(currentHP < 1)
                {
photonView.RPC("KillPlayer", PhotonTargets.All, killerID);
playerKilled = true;
}
}
}
}

[PunRPC]
void KillPlayer (int killerID)
    {
playerKilled = true;

if(photonView.isMine)
        {
soldierAnimation.gameObject.SetActive(true);
firstPersonView.SetActive(false);

localMouseLook.enabled = false;
http://fpsController.enabled = false;
playerWeapons.enabled = false;
playerWeapons.isFiring = false;

GameSettings.rc.PrepareRespawn(-killerID, false);
}

if(PhotonNetwork.isMasterClient)
        {
//Set killed player deaths
if(photonView.owner != null)
            {
int newDeaths = photonView.owner.customProperties["Deaths"] == null ? 1 : (int)photonView.owner.customProperties["Deaths"] + 1;
Hashtable setPlayerProperties = new Hashtable();
setPlayerProperties.Add("Deaths", newDeaths);
photonView.owner.SetCustomProperties(setPlayerProperties);

//Do not add kills nor team score if we killed ourselves (fell down etc.)
if(photonView.owner.ID != killerID)
                {
//Find killer player instance
PhotonPlayer killerPLayer = null;
PhotonPlayer[] allPlayers = PhotonNetwork.playerList;
for(int i = 0; i < allPlayers.Length; i++)
                    {
if(allPlayers[i].ID == killerID)
                        {
killerPLayer = allPlayers[i];
}
}

if(killerPLayer != null)
                    {
//Add kills for killer
int newKills = killerPLayer.customProperties["Kills"] == null ? 1 : (int)killerPLayer.customProperties["Kills"] + 1;
setPlayerProperties = new Hashtable();
setPlayerProperties.Add("Kills", newKills);
killerPLayer.SetCustomProperties(setPlayerProperties);

//Update team scores
if(GameSettings.currentGameMode == "TDM")
                        {
Hashtable setRoomProperties = new Hashtable();
int currentTeamScore = 0;

if((int)killerPLayer.customProperties["Team"] == 1)
                            {
currentTeamScore = PhotonNetwork.room.customProperties["TeamAScore"] != null ? (int)PhotonNetwork.room.customProperties["TeamAScore"] + 1: 1;
setRoomProperties.Add("TeamAScore", currentTeamScore);
}
if((int)killerPLayer.customProperties["Team"] == 2)
                            {
currentTeamScore = PhotonNetwork.room.customProperties["TeamBScore"] != null ? (int)PhotonNetwork.room.customProperties["TeamBScore"] + 1 : 1;
setRoomProperties.Add("TeamBScore", currentTeamScore);
}

if(setRoomProperties.Count > 0)
                            {
PhotonNetwork.room.SetCustomProperties(setRoomProperties);
}
}
}
}
}
}

if(PhotonNetwork.player.ID == killerID)
        {
//Check what weapon we used right before
string selectedWeaponNameTmp = "[" + lastWeaponName + "]";
string killedPlayerName = photonView.owner.name;
int killedPlayerTeam = (int)photonView.owner.customProperties["Team"];

if(lastBodyPart == -35)
            {
selectedWeaponNameTmp = "fell";
killedPlayerName = "down";
killedPlayerTeam = 0;
}
            else
            {
if(lastBodyPart == 0)
                {
selectedWeaponNameTmp += " -> Headshot";
}
}
//Notify others on kill and add cash
GameSettings.rc.ReportKill(killedPlayerName, selectedWeaponNameTmp, killedPlayerTeam);
GameSettings.rc.AddKillCash(lastBodyPart );
}

soldierAnimation.PlayKillAnimation();
}

int GetDMG (int weaponIndex, int bodyPart)
    {
if(weaponIndex > -1 && weaponIndex < playerWeapons.totalWeapons.Count)
        {
//For shotgun we divide damage for number of fractions
int divideBy = playerWeapons.totalWeapons[weaponIndex].fireType == PlayerWeapons.FireType.Shotgun ? 5 : 1;

if(bodyPart == 0 || bodyPart == 1)
            {
if(bodyPart == 0)
                {
return  playerWeapons.totalWeapons[weaponIndex].headDamage/divideBy;
}
                else
                {
return playerWeapons.totalWeapons[weaponIndex].torsoDamage/divideBy;
}
}
            else
            {
return playerWeapons.totalWeapons[weaponIndex].limbsDamage/divideBy;
}
}
        else
        {
return Mathf.Abs(weaponIndex);
}
}

void PlayHitSound ()
    {
playerAudio.Stop();
if(playerAudio.clip != hitSound)
        {
playerAudio.clip = hitSound;
}
playerAudio.Play();
}

void PlayWalkingSound ()
    {
//print ("Changed walking state");

CancelInvoke("PlayWalkingSoundInvoke");

stepLength = 0;

if(movementStateLocal == 0 || movementStateLocal == 1 || movementStateLocal == 2 || movementStateLocal == 4)
        {
if(movementStateLocal == 4)
            {
//On ladder
stepLength = 2.5f/fpsController.ladderSpeed;
}
            else
            {
if(movementStateLocal == 2)
                {
//Crouching
stepLength = 3.5f/fpsController.crouchSpeed;
}
                else
                {
if(movementStateLocal == 0)
                    {
stepLength = 3.5f/fpsController.walkSpeed;
}
                    else
                    {
stepLength = 3.5f/fpsController.runSpeed;
}
}
}
}

if(stepLength > 0)
        {
InvokeRepeating("PlayWalkingSoundInvoke", 0.09f, stepLength);
}
}

void PlayWalkingSoundInvoke ()
    {
walkingAudio.Stop();

if(fpsController.isMoving || soldierAnimation.isMoving)
        {
if(movementStateLocal == 4)
            {
//On ladder
walkingAudio.clip = ladderSounds[Random.Range(0, ladderSounds.Length - 1)];
}
            else
            {
//Walkig
walkingAudio.clip = walkingSounds[Random.Range(0, walkingSounds.Length - 1)];
}

walkingAudio.Play();
}
}
}
Sheyk
Sheyk
Avançado
Avançado

PONTOS : 3105
REPUTAÇÃO : 27
Idade : 24
Respeito as regras : (Jogo De FPS) Código para tirar HP ao entrar em lugares não permitidos WvDYdlf

Ir para o topo Ir para baixo

DÚVIDA Re: (Jogo De FPS) Código para tirar HP ao entrar em lugares não permitidos

Mensagem por Sheyk Sáb Jul 02, 2016 10:27 am

um pouco grande não ? hahahahaha :D :D :D :D :D
Sheyk
Sheyk
Avançado
Avançado

PONTOS : 3105
REPUTAÇÃO : 27
Idade : 24
Respeito as regras : (Jogo De FPS) Código para tirar HP ao entrar em lugares não permitidos WvDYdlf

Ir para o topo Ir para baixo

DÚVIDA Re: (Jogo De FPS) Código para tirar HP ao entrar em lugares não permitidos

Mensagem por JohnRambo Sáb Jul 02, 2016 10:32 am

É sim kkk mas peço que dá próxima vez use a caixa de códigos que o fórum oferece
JohnRambo
JohnRambo
Moderador

Masculino PONTOS : 4927
REPUTAÇÃO : 661
Idade : 23
Áreas de atuação : Unity;
Programação;
Música e Sonorização;
Graduado em Análise e Desenvolvimento de Sistemas;
Respeito as regras : (Jogo De FPS) Código para tirar HP ao entrar em lugares não permitidos Aad8pUi

Ir para o topo Ir para baixo

DÚVIDA Re: (Jogo De FPS) Código para tirar HP ao entrar em lugares não permitidos

Mensagem por Sheyk Sáb Jul 02, 2016 10:46 am

OK, desculpe-me!!! 
é porque sou novato por aqui e não sei quase nada...
mais irei dar meu máximo para seguir as regras!!!
Sheyk
Sheyk
Avançado
Avançado

PONTOS : 3105
REPUTAÇÃO : 27
Idade : 24
Respeito as regras : (Jogo De FPS) Código para tirar HP ao entrar em lugares não permitidos WvDYdlf

Ir para o topo Ir para baixo

DÚVIDA Re: (Jogo De FPS) Código para tirar HP ao entrar em lugares não permitidos

Mensagem por JohnRambo Sáb Jul 02, 2016 10:50 am

Sem problemas,  não infringiste regra alguma, entenda mais por aqui: https://www.schultzgames.com/t1292-___como-utilizar-o-forum___-principais-botoes-e-suas-funcoes

Quanto ao script está quase pronto
JohnRambo
JohnRambo
Moderador

Masculino PONTOS : 4927
REPUTAÇÃO : 661
Idade : 23
Áreas de atuação : Unity;
Programação;
Música e Sonorização;
Graduado em Análise e Desenvolvimento de Sistemas;
Respeito as regras : (Jogo De FPS) Código para tirar HP ao entrar em lugares não permitidos Aad8pUi

Ir para o topo Ir para baixo

DÚVIDA Re: (Jogo De FPS) Código para tirar HP ao entrar em lugares não permitidos

Mensagem por JohnRambo Sáb Jul 02, 2016 11:08 am

mas antes eu preciso que voce corrija os varios erros que existem neste script. tem varios lugares que faltam ;     }     )
JohnRambo
JohnRambo
Moderador

Masculino PONTOS : 4927
REPUTAÇÃO : 661
Idade : 23
Áreas de atuação : Unity;
Programação;
Música e Sonorização;
Graduado em Análise e Desenvolvimento de Sistemas;
Respeito as regras : (Jogo De FPS) Código para tirar HP ao entrar em lugares não permitidos Aad8pUi

Ir para o topo Ir para baixo

DÚVIDA Re: (Jogo De FPS) Código para tirar HP ao entrar em lugares não permitidos

Mensagem por Sheyk Sáb Jul 02, 2016 11:19 am

Ok
Sheyk
Sheyk
Avançado
Avançado

PONTOS : 3105
REPUTAÇÃO : 27
Idade : 24
Respeito as regras : (Jogo De FPS) Código para tirar HP ao entrar em lugares não permitidos WvDYdlf

Ir para o topo Ir para baixo

DÚVIDA Re: (Jogo De FPS) Código para tirar HP ao entrar em lugares não permitidos

Mensagem por Sheyk Sáb Jul 02, 2016 4:22 pm

:D
Sheyk
Sheyk
Avançado
Avançado

PONTOS : 3105
REPUTAÇÃO : 27
Idade : 24
Respeito as regras : (Jogo De FPS) Código para tirar HP ao entrar em lugares não permitidos WvDYdlf

Ir para o topo Ir para baixo

DÚVIDA Re: (Jogo De FPS) Código para tirar HP ao entrar em lugares não permitidos

Mensagem por JohnRambo Sáb Jul 02, 2016 10:41 pm

Pronto? Repasse o script usando a caixinha de códigos pra ele não perder componentes
JohnRambo
JohnRambo
Moderador

Masculino PONTOS : 4927
REPUTAÇÃO : 661
Idade : 23
Áreas de atuação : Unity;
Programação;
Música e Sonorização;
Graduado em Análise e Desenvolvimento de Sistemas;
Respeito as regras : (Jogo De FPS) Código para tirar HP ao entrar em lugares não permitidos Aad8pUi

Ir para o topo Ir para baixo

DÚVIDA Re: (Jogo De FPS) Código para tirar HP ao entrar em lugares não permitidos

Mensagem por Sheyk Dom Jul 03, 2016 1:21 am

Código:
//New FPS
//Staff @2016

using UnityEngine;
using System.Collections;
using Hashtable = ExitGames.Client.Photon.Hashtable; //Replace default Hashtables with Photon hashtables

public class PlayerNetwork : Photon.MonoBehaviour
{

   //This is main script that coordinate our player in game, it decides which component to enable/disable
   //Also it sync's our data with remote instances over network

   public SoldierAnimation soldierAnimation;
   public Renderer soldierBody;
   public Material teamALook;
   public Material teamBLook;
   public Material fpsHandMaterial;
   public PlayerWeapons playerWeapons;
   public GameObject firstPersonView;

   public Transform nameLabelTransform;
   public GUIText nameLabel;
   public GUIText nameLabelShadow;

   public AudioSource playerAudio;
   public AudioSource walkingAudio;

   public AudioClip hitSound;
   public AudioClip[] walkingSounds;
   public AudioClip[] ladderSounds;

   public Collider[] headHitBoxes;
   public Collider[] torsoHitBoxes;
   public Collider[] limbsHitBoxes;

   Vector3 playerPos = Vector3.zero;
   [HideInInspector]
   public Vector3 aimPos = Vector3.zero;
   Vector3 smoothAimPos = Vector3.zero;
   float positionSmoother = 17.5f;
   float d;

   [HideInInspector]
   public FPSController fpsController;
   FPSMouseLook localMouseLook;
   [HideInInspector]
   public FPSMouseLook cameraMouseLook;
   [HideInInspector]
   public Transform thisT;
   //[HideInInspector]
   //public RoomController rc;
   [HideInInspector]
   public int playerID;
   [HideInInspector]
   public bool playerKilled = false;
   
   int currentWeaponIndex = -1;
   int previousWeaponIndex = -1;
   bool isFiringRemote = false;
   int playerTeam;
   Camera mainCamera;
   Transform mainCameraT;
   Vector3 screenPos; //For name label display
   float offset;
   //Save references incase we kill this player
   string lastWeaponName = "";
   int lastBodyPart = -1;
   
   //Position Interpolation Sync
   double interpolationBackTime = 0.37d;
   
   internal struct State
    {
      internal double timestamp;
      internal Vector3 pos;
      internal Quaternion rot;
   }

   //double currentTime;
   
   // We store twenty states with "playback" information
   State[] m_BufferedState = new State[20];
   // Keep track of what slots are used
   int m_TimestampCount;
   int movementStateLocal = -1;
   int receivedMovementState = -1;
   float stepLength; //Used for playing walking sounds
   
   // Use this for initialization
   void Start ()
    {
      photonView.synchronization = ViewSynchronization.Unreliable;

      localMouseLook = GetComponent<FPSMouseLook>();
      fpsController = GetComponent<FPSController>();
      fpsController.pn = this;

      playerWeapons.playerNetwork = this;
      playerWeapons.soldierAnimation = soldierAnimation;
      playerWeapons.fpsController = fpsController;
      playerWeapons.QuickSetup(photonView.isMine);

      gameObject.name = photonView.owner.name;
      thisT = transform;

      playerKilled = false;

      gameObject.layer = 2; //Set layer to Ignore Raycast

      if(!photonView.isMine)
        {
         //Deactivate all scripts and object that are not used by remote instance
         localMouseLook.enabled = false;
         fpsController.enabled = false;
         playerWeapons.enabled = false;
         firstPersonView.SetActive(false);
         if(!soldierAnimation.gameObject.activeSelf)
            {
            soldierAnimation.gameObject.SetActive(true);
         }
         soldierAnimation.playerWeapons = playerWeapons;
         soldierAnimation.playerNetwork = this;
         soldierAnimation.Setup();

         SetupBoxes(headHitBoxes, HitBox.BodyPart.Head);
         SetupBoxes(torsoHitBoxes, HitBox.BodyPart.Torso);
         SetupBoxes(limbsHitBoxes, HitBox.BodyPart.Limbs);

         //Add this player to reference
         GameSettings.rc.otherPlayers.Add(this);
      }
        else
        {
         firstPersonView.SetActive(true);
         soldierAnimation.gameObject.SetActive(false);
         cameraMouseLook = playerWeapons.playerCamera.GetComponent<FPSMouseLook>();
         nameLabelTransform.gameObject.SetActive(false);
         gameObject.tag = "Player";
      }

      if(PhotonNetwork.isMasterClient)
        {
         //Set player HP
         Hashtable setPlayerData = new Hashtable();
         setPlayerData.Add("PlayerHP", (int)100);
         photonView.owner.SetCustomProperties(setPlayerData);
      }

      playerTeam = (int)photonView.owner.customProperties["Team"];
      playerID = photonView.owner.ID;

      if(playerTeam == 1 || playerTeam == 2)
        {
         if(playerTeam == 1)
            {
            soldierBody.sharedMaterial = teamALook;
         }
            else
            {
            soldierBody.sharedMaterial = teamBLook;
         }

         if(photonView.isMine)
            {
            fpsHandMaterial.SetTexture("_MainTex", soldierBody.sharedMaterial.GetTexture("_MainTex"));
            fpsHandMaterial.color = soldierBody.sharedMaterial.color;
         }
            else
            {
            nameLabel.text = photonView.name;
            nameLabelShadow.text = photonView.name;
            nameLabel.color = playerTeam == 1 ? GameSettings.teamAColor : GameSettings.teamBColor;
         }
      }
   }

   void SetupBoxes (Collider[] tmpBoxes, HitBox.BodyPart bp)
    {
      for(int i = 0; i < tmpBoxes.Length; i++)
        {
         tmpBoxes[i].isTrigger = true;
         tmpBoxes[i].gameObject.AddComponent<HitBox>().AssignVariables(this, bp);
         tmpBoxes[i].tag = "Body";
      }
   }

   //Sync player over network
   void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
    {
      if (stream.isWriting)
        {
         //Send data
         if(!thisT)
            return;

         stream.SendNext(thisT.position);
         stream.SendNext(playerWeapons.playerCamera.position + playerWeapons.playerCamera.forward * 100);
         stream.SendNext(playerWeapons.globalWeaponIndex);
         stream.SendNext(playerWeapons.isFiring);
         stream.SendNext(fpsController.movementState);
      }
        else
        {
         //Receive data
         playerPos = (Vector3)stream.ReceiveNext();
         aimPos = (Vector3)stream.ReceiveNext();
         currentWeaponIndex = (int)stream.ReceiveNext();
         isFiringRemote = (bool)stream.ReceiveNext();
         soldierAnimation.movementState = (int)stream.ReceiveNext();


         // Shift buffer contents, oldest data erased, 18 becomes 19, ... , 0 becomes 1
         for (int i=m_BufferedState.Length-1;i>=1;i--)
         {
            m_BufferedState[i] = m_BufferedState[i-1];
         }
         
         // Save currect received state as 0 in the buffer, safe to overwrite after shifting
         State state = new State();
         state.timestamp = info.timestamp;
         state.pos = playerPos;
         //state.rot = rot;
         m_BufferedState[0] = state;
         
         // Increment state count but never exceed buffer size
         m_TimestampCount = Mathf.Min(m_TimestampCount + 1, m_BufferedState.Length);
         
         // Check integrity, lowest numbered state in the buffer is newest and so on
         for (int i=0;i<m_TimestampCount-1;i++)
         {
            if (m_BufferedState[i].timestamp < m_BufferedState[i+1].timestamp)
               Debug.Log("State inconsistent");
         }
      }
   }
   
   // Update is called once per frame
   void Update ()
    {
      if(!photonView.isMine)
        {
         InterpolatePosition ();

         smoothAimPos = Vector3.Lerp(smoothAimPos, aimPos, Time.deltaTime * positionSmoother);

         if(aimPos != Vector3.zero)
            {
            thisT.LookAt(new Vector3(smoothAimPos.x, thisT.position.y, smoothAimPos.z));
            playerWeapons.playerCamera.LookAt(smoothAimPos);
         }

         if(isFiringRemote)
            {
            playerWeapons.FireRemote();
         }

         if(previousWeaponIndex != currentWeaponIndex)
            {
            previousWeaponIndex = currentWeaponIndex;
            playerWeapons.globalWeaponIndex = currentWeaponIndex;
            playerWeapons.SwitchWeaponRemote();
         }

         //Show name label for our teammates
         if(!playerKilled && ((playerTeam == GameSettings.ourTeam && GameSettings.currentGameMode != "FFA") || GameSettings.ourTeam == 0))
            {
            if(!nameLabelTransform.gameObject.activeSelf)
                {
               nameLabelTransform.gameObject.SetActive(true);
            }
            
            if(!mainCamera || !mainCamera.gameObject.activeInHierarchy)
                {
               if(Camera.main)
                    {
                  mainCamera = Camera.main;
                  mainCameraT = mainCamera.transform;
               }
            }
                else
                {
               offset = Vector3.Distance(mainCameraT.position, thisT.position)/50;
               screenPos = mainCamera.WorldToViewportPoint(new Vector3(thisT.position.x, thisT.position.y + 2.6f + offset, thisT.position.z));

               if(screenPos.z > 0)
                    {
                  nameLabelTransform.position = new Vector3(screenPos.x, screenPos.y);
               }
                    else
                    {
                  nameLabelTransform.position = new Vector3(-350, -350);
               }
            }

            nameLabelTransform.eulerAngles = Vector3.zero;
         }
            else
            {
            if(nameLabelTransform.gameObject.activeSelf)
                {
               nameLabelTransform.gameObject.SetActive(false);
            }
         }

         receivedMovementState = soldierAnimation.movementState;
      }
        else
        {
         //Send cameraFOV to reduce mouse sensitivity when aiming
         //localMouseLook.cameraFOV = playerWeapons.mainPlayerCamera.fieldOfView;
         //cameraMouseLook.cameraFOV = playerWeapons.mainPlayerCamera.fieldOfView;

         receivedMovementState = fpsController.movementState;
      }

      //Play footstep sound for both local and remote player instances
      if(!playerKilled)
        {
         if(movementStateLocal != receivedMovementState)
            {
            movementStateLocal = receivedMovementState;
            PlayWalkingSound();
         }
      }
        else
        {
         if(walkingAudio.isPlaying)
            {
            walkingAudio.Stop();
         }
      }
   }
   
   void InterpolatePosition ()
    {
      d = Vector3.Distance(thisT.position, m_BufferedState[0].pos);
      soldierAnimation.isMoving = d > 0.1f;

      double currentTime = PhotonNetwork.time;
      double interpolationTime = currentTime - interpolationBackTime;
      // We have a window of interpolationBackTime where we basically play
      // By having interpolationBackTime the average ping, you will usually use interpolation.
      // And only if no more data arrives we will use extrapolation
      
      // Use interpolation
      // Check if latest state exceeds interpolation time, if this is the case then
      // it is too old and extrapolation should be used
      
      if (m_BufferedState[0].timestamp > interpolationTime)
        {
         for (int i=0;i<m_TimestampCount;i++)
            {
            // Find the state which matches the interpolation time (time+0.1) or use last state
            if (m_BufferedState[i].timestamp <= interpolationTime || i == m_TimestampCount-1)
                {
               // The state one slot newer (<100ms) than the best playback state
               State rhs = m_BufferedState[Mathf.Max(i-1, 0)];
               // The best playback state (closest to 100 ms old (default time))
               State lhs = m_BufferedState[i];
               
               // Use the time between the two slots to determine if interpolation is necessary
               double length = rhs.timestamp - lhs.timestamp;
               float t = 0.0F;
               // As the time difference gets closer to 100 ms t gets closer to 1 in
               // which case rhs is only used
               if (length > 0.0001)
                    {
                  t = (float)((interpolationTime - lhs.timestamp) / length);
               }
               
               // if t=0 => lhs is used directly
               thisT.position = Vector3.Lerp(lhs.pos, rhs.pos, t);
               //transform.localRotation = Quaternion.Slerp(lhs.rot, rhs.rot, t);
               return;
            }
         }
      }
        else
        {
         // Use extrapolation. Here we do something really simple and just repeat the last
         // received state. You can do clever stuff with predicting what should happen

         State latest = m_BufferedState[0];
         
         thisT.position = latest.pos;
         //transform.localRotation = latest.rot;
         
         //print ("Moving DIrectly to latest pos " + Random.Range(111, 333).ToString());
      }
   }

   //Called from Weapon.cs when player shooting single fire weapons
   public void FireSingleRemote()
    {
      photonView.RPC("FireRemoteRPC", PhotonTargets.Others);
   }

   [PunRPC]
   void FireRemoteRPC()
    {
      playerWeapons.FireRemote();
   }

   //Reload Sync
   public void DoReload ()
    {
      photonView.RPC("DoReloadRemote", PhotonTargets.Others);
   }

   [PunRPC]
   void DoReloadRemote()
    {
      if(playerWeapons.currentSelectedWeapon)
        {
         playerWeapons.currentSelectedWeapon.ReloadNetworkSync();
      }
   }

   //Do player damage, called from HitBox.cs
   public void ApplyDamage(int[] values)
    {
      if(!playerKilled && (playerTeam != GameSettings.ourTeam || photonView.isMine || GameSettings.currentGameMode == "FFA"))
        {
         photonView.RPC("DamageRemote", PhotonTargets.All, values, PhotonNetwork.player.ID);
      }
   }

   [PunRPC]
   void DamageRemote (int[] values, int killerID)
    {
      if(photonView.isMine)
        {
         GameSettings.rc.DoHitDetector((int)values[2]);
         fpsController.fallSlowDown = 0.5f;

         PlayHitSound();
      }
        else
        {
         soldierAnimation.DoHitMovement();
      }

      if(!playerKilled)
        {
         if(PhotonNetwork.player.ID == killerID)
            {
            //Save temp references
            lastWeaponName = GameSettings.rc.ourPlayer ? GameSettings.rc.ourPlayer.playerWeapons.currentSelectedWeapon.weaponName : "";
            lastBodyPart = values[1];
         }

         if(PhotonNetwork.isMasterClient)
            {
            int currentHP = photonView.owner.customProperties["PlayerHP"] != null ? (int)photonView.owner.customProperties["PlayerHP"] : 100;
            currentHP -= GetDMG((int)values[0], (int)values[1]);
            Hashtable setPlayerData = new Hashtable();
            setPlayerData.Add("PlayerHP", currentHP); //Setup player HP by master client
            photonView.owner.SetCustomProperties(setPlayerData);

            if(currentHP < 1)
                {
               photonView.RPC("KillPlayer", PhotonTargets.All, killerID);
               playerKilled = true;
            }
         }
      }
   }

   [PunRPC]
   void KillPlayer (int killerID)
    {
      playerKilled = true;

      if(photonView.isMine)
        {
         soldierAnimation.gameObject.SetActive(true);
         firstPersonView.SetActive(false);

         localMouseLook.enabled = false;
         //fpsController.enabled = false;
         playerWeapons.enabled = false;
         playerWeapons.isFiring = false;

         GameSettings.rc.PrepareRespawn(-killerID, false);
      }

      if(PhotonNetwork.isMasterClient)
        {
         //Set killed player deaths
         if(photonView.owner != null)
            {
            int newDeaths = photonView.owner.customProperties["Deaths"] == null ? 1 : (int)photonView.owner.customProperties["Deaths"] + 1;
            Hashtable setPlayerProperties = new Hashtable();
            setPlayerProperties.Add("Deaths", newDeaths);
            photonView.owner.SetCustomProperties(setPlayerProperties);

            //Do not add kills nor team score if we killed ourselves (fell down etc.)
            if(photonView.owner.ID != killerID)
                {
               //Find killer player instance
               PhotonPlayer killerPLayer = null;
               PhotonPlayer[] allPlayers = PhotonNetwork.playerList;
               for(int i = 0; i < allPlayers.Length; i++)
                    {
                  if(allPlayers[i].ID == killerID)
                        {
                     killerPLayer = allPlayers[i];
                  }
               }

               if(killerPLayer != null)
                    {
                  //Add kills for killer
                  int newKills = killerPLayer.customProperties["Kills"] == null ? 1 : (int)killerPLayer.customProperties["Kills"] + 1;
                  setPlayerProperties = new Hashtable();
                  setPlayerProperties.Add("Kills", newKills);
                  killerPLayer.SetCustomProperties(setPlayerProperties);

                  //Update team scores
                  if(GameSettings.currentGameMode == "TDM")
                        {
                     Hashtable setRoomProperties = new Hashtable();
                     int currentTeamScore = 0;

                     if((int)killerPLayer.customProperties["Team"] == 1)
                            {
                        currentTeamScore = PhotonNetwork.room.customProperties["TeamAScore"] != null ? (int)PhotonNetwork.room.customProperties["TeamAScore"] + 1: 1;
                        setRoomProperties.Add("TeamAScore", currentTeamScore);
                     }
                     if((int)killerPLayer.customProperties["Team"] == 2)
                            {
                        currentTeamScore = PhotonNetwork.room.customProperties["TeamBScore"] != null ? (int)PhotonNetwork.room.customProperties["TeamBScore"] + 1 : 1;
                        setRoomProperties.Add("TeamBScore", currentTeamScore);
                     }

                     if(setRoomProperties.Count > 0)
                            {
                        PhotonNetwork.room.SetCustomProperties(setRoomProperties);
                     }
                  }
               }
            }
         }
      }

      if(PhotonNetwork.player.ID == killerID)
        {
         //Check what weapon we used right before
         string selectedWeaponNameTmp = "[" + lastWeaponName + "]";
         string killedPlayerName = photonView.owner.name;
         int killedPlayerTeam = (int)photonView.owner.customProperties["Team"];

         if(lastBodyPart == -35)
            {
            selectedWeaponNameTmp = "fell";
            killedPlayerName = "down";
            killedPlayerTeam = 0;
         }
            else
            {
            if(lastBodyPart == 0)
                {
               selectedWeaponNameTmp += " -> Headshot";
            }
         }
         //Notify others on kill and add cash
         GameSettings.rc.ReportKill(killedPlayerName, selectedWeaponNameTmp, killedPlayerTeam);
         GameSettings.rc.AddKillCash(lastBodyPart );
      }

      soldierAnimation.PlayKillAnimation();
   }

   int GetDMG (int weaponIndex, int bodyPart)
    {
      if(weaponIndex > -1 && weaponIndex < playerWeapons.totalWeapons.Count)
        {
         //For shotgun we divide damage for number of fractions
         int divideBy = playerWeapons.totalWeapons[weaponIndex].fireType == PlayerWeapons.FireType.Shotgun ? 5 : 1;

         if(bodyPart == 0 || bodyPart == 1)
            {
            if(bodyPart == 0)
                {
               return  playerWeapons.totalWeapons[weaponIndex].headDamage/divideBy;
            }
                else
                {
               return playerWeapons.totalWeapons[weaponIndex].torsoDamage/divideBy;
            }
         }
            else
            {
            return playerWeapons.totalWeapons[weaponIndex].limbsDamage/divideBy;
         }
      }
        else
        {
         return Mathf.Abs(weaponIndex);
      }
   }

   void PlayHitSound ()
    {
      playerAudio.Stop();
      if(playerAudio.clip != hitSound)
        {
         playerAudio.clip = hitSound;
      }
      playerAudio.Play();
   }

   void PlayWalkingSound ()
    {
      //print ("Changed walking state");

      CancelInvoke("PlayWalkingSoundInvoke");

      stepLength = 0;

      if(movementStateLocal == 0 || movementStateLocal == 1 || movementStateLocal == 2 || movementStateLocal == 4)
        {
         if(movementStateLocal == 4)
            {
            //On ladder
            stepLength = 2.5f/fpsController.ladderSpeed;
         }
            else
            {
            if(movementStateLocal == 2)
                {
               //Crouching
               stepLength = 3.5f/fpsController.crouchSpeed;
            }
                else
                {
               if(movementStateLocal == 0)
                    {
                  stepLength = 3.5f/fpsController.walkSpeed;
               }
                    else
                    {
                  stepLength = 3.5f/fpsController.runSpeed;
               }
            }
         }
      }

      if(stepLength > 0)
        {
         InvokeRepeating("PlayWalkingSoundInvoke", 0.09f, stepLength);
      }
   }

   void PlayWalkingSoundInvoke ()
    {
      walkingAudio.Stop();

      if(fpsController.isMoving || soldierAnimation.isMoving)
        {
         if(movementStateLocal == 4)
            {
            //On ladder
            walkingAudio.clip = ladderSounds[Random.Range(0, ladderSounds.Length - 1)];
         }
            else
            {
            //Walkig
            walkingAudio.clip = walkingSounds[Random.Range(0, walkingSounds.Length - 1)];
         }

         walkingAudio.Play();
      }
   }
}
Sheyk
Sheyk
Avançado
Avançado

PONTOS : 3105
REPUTAÇÃO : 27
Idade : 24
Respeito as regras : (Jogo De FPS) Código para tirar HP ao entrar em lugares não permitidos WvDYdlf

Ir para o topo Ir para baixo

DÚVIDA Re: (Jogo De FPS) Código para tirar HP ao entrar em lugares não permitidos

Mensagem por Sheyk Dom Jul 03, 2016 1:21 am

agora ta certo ?
Sheyk
Sheyk
Avançado
Avançado

PONTOS : 3105
REPUTAÇÃO : 27
Idade : 24
Respeito as regras : (Jogo De FPS) Código para tirar HP ao entrar em lugares não permitidos WvDYdlf

Ir para o topo Ir para baixo

DÚVIDA Re: (Jogo De FPS) Código para tirar HP ao entrar em lugares não permitidos

Mensagem por MarcosSchultz Dom Jul 03, 2016 7:42 pm

Pegou este script pronto de algum lugar?

Estão faltando um monte de scripts adicionais para que possamos ajudar... seria melhor zipar o projeto e enviar para que possamos ver. Ou terá que enviar os scripts que faltam como:

SoldierAnimation, PlayerWeapons, FPSController, FPSMouseLook, Photon, e toda a parte do Photon e suas bibliotecas.

O HP neste script que você passou não é presente nele... apenas é feita uma indicão, mas o HP real está em outro script. É uma propriedade chamada ""PlayerHP""

O que você pode fazer neste script é deixar esta variável verdadeira: "playerKilled"...
MarcosSchultz
MarcosSchultz
Administrador

Masculino PONTOS : 64727
REPUTAÇÃO : 2650
Idade : 27
Áreas de atuação : Administrador do fórum
Respeito as regras : (Jogo De FPS) Código para tirar HP ao entrar em lugares não permitidos Aad8pUi

https://www.schultzgames.com

Ir para o topo Ir para baixo

Ir para o topo

- Tópicos semelhantes

 
Permissões neste sub-fórum
Não podes responder a tópicos